[Django]-Two or More Django Projects in Same Droplet via Subdomain

9👍

The principle is to use nginx as a broker for the HTTP requests, proxying them to two gUnicorn instances running your two Django apps in parallel, depending on their Host header.

For that you need to setup two different server configurations with nginx. Each with a different server_name. Those two servers will proxy to two different gUnicorn instances running on different ports.

Nginx configuration

# Server definition for project A
server {
    listen             80;
    server_name        <projectA domain name>;

    location / {
        # Proxy to gUnicorn.
        proxy_pass             http://127.0.0.1:<projectA gUnicorn port>;
        # etc...
    }
}

# Server definition for project B
server {
    listen             80;
    server_name        <projectB domain name>;

    location / {
        # Proxy to gUnicorn on a different port.
        proxy_pass             http://127.0.0.1:<projectB gUnicorn port>;
        # etc...
    }
}

It might be better to split the two definitions in separate files. Also remember to link them in /etc/nginx/sites-enabled/.

Upstart configuration

These two files need to be put in /etc/init/.

projecta_gunicorn.conf:

description "Gunicorn daemon for Django project A"

start on (local-filesystems and net-device-up IFACE=eth0)
stop on runlevel [!12345]

# If the process quits unexpectadly trigger a respawn
respawn

setuid django
setgid django
chdir /home/django/<path to projectA>

exec /home/django/<path to project A virtualenv>/bin/gunicorn --config /home/django/<path to project A gunicorn.py> <projectA name>.wsgi:application

projectb_gunicorn.conf:

description "Gunicorn daemon for Django project B"

start on (local-filesystems and net-device-up IFACE=eth0)
stop on runlevel [!12345]

# If the process quits unexpectadly trigger a respawn
respawn

setuid django
setgid django
chdir /home/django/<path to projectB>

exec /home/django/<path to projectB virtualenv>/bin/gunicorn --config /home/django/<path to projectB gunicorn.py> <projectB name>.wsgi:application

gUnicorn configuration

Project A gunicorn.py:

bind = '127.0.0.1:<projectA gUnicorn port>'
raw_env = 'DJANGO_SETTINGS_MODULE=<projectA name>.settings'

Project B gunicorn.py:

bind = '127.0.0.1:<projectB gUnicorn port>'
raw_env = 'DJANGO_SETTINGS_MODULE=<projectB name>.settings'
👤aumo

Leave a comment