NOTE: ProjectFolderName and ProjectName can be kept the same or different
Setting the project folder
Creating Project folder using GIT & Changing Current Directory ( Use token@ for Private repo )
git clone [Git_link]
cd ~/ProjectFolderName
OR Just
Create Project folder & Changing Current Directory
mkdir ~/ProjectFolderName
cd ~/ProjectFolderName
Creating & activating Virtual env
virtualenv env
source env/bin/activate
Installing django and gunicorn or requirements.txt
pip install django gunicorn
pip install -r requirements.txt
Creating Django app (or just skip this step if git clone)
django-admin startproject AppName ~/ProjectFolderName
Make Sure To Create and Edit the .env file
Also Change The Debug To False
Migrating the database
python manage.py makemigrations
python manage.py migrate
Testing Project Normaly for any Errors
python manage.py runserver 0.0.0.0:8000
Once The Above Test pass , Test using gunicorn
gunicorn --bind 0.0.0.0:8000 AppName.wsgi
Once All Works Great File Setup is Complete
Deactivate the virtual env
deactivate
Configuring Gunicorn
Creating and Editing the Socket Unit File
sudo nano /etc/systemd/system/ProjectName.socket
Inside The File Add The Below Code
[Unit]
Description=gunicorn socket
[Socket]
ListenStream=/run/ProjectName.sock
[Install]
WantedBy=sockets.target
Save by pressing Ctrl+X Then Y Then Enter
Creating and Editing the Service Unit File
sudo nano /etc/systemd/system/ProjectName.service
Inside The File Add The Below Code
[Unit]
Description=gunicorn daemon
Requires=ProjectName.socket
After=network.target
[Service]
User=UserName
Group=www-data
WorkingDirectory=/home/UserName/ProjectFolderName
ExecStart=/home/UserName/ProjectFolderName/env/bin/gunicorn \
--access-logfile - \
--workers 3 \
--bind unix:/run/ProjectName.sock \
AppName.wsgi:application
[Install]
WantedBy=multi-user.target
Save by pressing Ctrl+X Then Y Then Enter
Starting and Enabling the Socket
sudo systemctl start ProjectName.socket
sudo systemctl enable ProjectName.socket
Configuring Nginx
Creating and Editing the Nginx Configuration File
sudo nano /etc/nginx/sites-available/ProjectName
Inside The File Add The Below Code
server {
listen 80;
server_name www.lazythinkers.in;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/UserName/ProjectFolderName;
}
location / {
include proxy_params;
proxy_pass http://unix:/run/ProjectName.sock;
}
}
Save by pressing Ctrl+X Then Y Then Enter
Enabling the Nginx Configuration & Restarting Nginx
sudo ln -s /etc/nginx/sites-available/ProjectName /etc/nginx/sites-enabled/
sudo systemctl restart nginx
The App Should Be Up and Running
Important Notice
Make sure to enable https: on to your domain ( Check Home page for steps )
Conclusion
You now have Django running with Gunicorn behind Nginx. Your Django application should now be accessible through your domain or IP address.