How I create multiple django site for subdomain1 and subdomain2, using gunicorn + nginx + systemd | ubuntu 20.04 | DigitalOcean

Prerequisite:

1.Can run gunicorn on your env

gunicorn --bind 0.0.0.0:9001 myapp.wsgi
2.Added subdomain on droplet networking.
3.Root access.
4.Install certbot nginx
sudo apt install certbot python3-certbot-nginx
.

Create multiple django site for subdomain1 and subdomain2, using gunicorn + nginx + systemd | DigitalOcean.

1.Make sure you already installed the gunicorn on your django env

pip install gunicorn

2.Create new socket file on

sudo nano /etc/systemd/system/gunicorn_subdomain1.socket

[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/gunicorn_subdomain1.sock

[Install]
WantedBy=sockets.target

3.Create new service file on

sudo nano /etc/systemd/system/gunicorn_subdomain1.service

[Unit]
Description=gunicorn daemon
Requires=gunicorn_subdomain1.socket
After=network.target

[Service]
User=myuser
Group=www-data
WorkingDirectory=/home/myuser/django/subdomain1
ExecStart=/home/myuser/django/subdomain1/bin/gunicorn \
    --access-logfile - \
    --workers 3 \
    --bind unix:/run/gunicorn_subdomain1.sock \
    myapp.wsgi:application

[Install]
WantedBy=multi-user.target

4.Start & Enable the gunicorn_subdomain1 service.

sudo systemctl start gunicorn_subdomain1
sudo systemctl enable gunicorn_subdomain1
Lets check if the gunicorn_subdomain1 service is running
sudo systemctl status gunicorn_subdomain1
. If its running and active then, lets proceed.

5.Create new site subdomain1 config on nginx

sudo nano /etc/nginx/sites-available/subdomain1

server {
    server_name subdomain1.myapp.com;
    location = /favicon.ico { access_log off; log_not_found off; }
    location /static {
        root /home/myuser/django/subdomain1;
    }
    location /files {
        root /home/myuser/django/subdomain1;
    }      
	location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarder-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://unix:/run/gunicorn_subdomain1.sock;
    }
}

Lets enable the subdomain1 config nginx

sudo ln -s /etc/nginx/sites-available/subdomain1 /etc/nginx/sites-enabled/

Once enabled then lets update/restart the nginx server

sudo nginx -t && sudo systemctl restart nginx

Lets install ssl with letsencrypt

sudo certbot --nginx -d subdomain1.myapp.com

It will be the same procedure for subdomain2 just follow thru again the instruction and your good to go. ;)

Add new comment