How to Deploy Django with Gunicorn and Nginx on Ubuntu 24.04

Aybars Altınyay
Aybars Altınyay
Platform Engineer & Technical Writer
IntermediateUpdated Nov 17, 202618 min read~45+ minutes total
PythonDjangoGunicornNginxUbuntu 24.04WSGIsystemdDeployment
Last reviewed:
Tutorial
How to Deploy Django with Gunicorn and Nginx on Ubuntu 24.04
rafftechnologies.com/learn
On this page

Prerequisites

  • A Raff Linux VM running Ubuntu 24.04, SSH access with a non-root sudo user, a domain pointed to the VM, and TCP ports 80 and 443 available for Nginx

Launch your Django app on your own Ubuntu 24.04 server.

Tested on 2 vCPU and 4 GB RAM: $17.99 a month

  1. 1Pick a Linux imageUbuntu, Debian and more, with your SSH key added.
  2. 2Choose a sizeFrom $4.99 a month. Resize when your app grows.
  3. 3Connect over SSHYour server is up in about 55 seconds.

Ubuntu, Debian and other Linux distributions with full root and SSH access, up and running in about 55 seconds.

Deploying Django with Gunicorn and Nginx on Ubuntu 24.04 gives each layer one clear responsibility: Django handles application logic, Gunicorn runs the WSGI application, systemd manages the Gunicorn process, and Nginx handles public HTTP/HTTPS traffic and static files. You can use this pattern on a Raff Linux VM without exposing Django's development server or a raw Gunicorn port to the internet.

Django's production checklist explicitly says manage.py runserver is not designed for production and recommends a production WSGI or ASGI server instead. Gunicorn's deployment documentation recommends placing Gunicorn behind a proxy such as Nginx. The worker-count formula often quoted for Gunicorn is only a starting point; the correct count depends on CPU, memory, database connections, request behavior, and measured load.

This tutorial creates a small Django app, keeps SECRET_KEY outside source control, runs Gunicorn as a non-root systemd service over a Unix socket, serves collected static files with Nginx, keeps the application port private, and finishes with HTTPS and Django's deployment checks.

Prerequisites:

  • A Raff Linux VM running Ubuntu 24.04
  • SSH access with a non-root sudo user
  • A domain such as example.com pointing to the VM
  • TCP ports 80 and 443 available for Nginx
  • No requirement to expose Gunicorn directly to the public internet

Step 1 — Install Python and Nginx and Create a Django Service User

Update package metadata and install the packages used by this deployment:

Bash
sudo apt update sudo apt install -y python3-venv nginx curl

Create a dedicated non-login user for the Django application:

Bash
sudo useradd --system \ --home /srv/mysite \ --create-home \ --shell /usr/sbin/nologin \ djangoapp

Create the application directory and give the service user ownership:

Bash
sudo mkdir -p /srv/mysite/app sudo chown -R djangoapp:djangoapp /srv/mysite

Confirm Python and Nginx are available:

Bash
python3 --version nginx -v systemctl is-active nginx

Do not depend on an exact Python patch version in automation; Ubuntu security updates can change it within the supported 3.12 series.

Verify: Python should run, Nginx should report a version, and systemctl is-active nginx should return active.

Step 2 — Create a Virtual Environment and Install Django and Gunicorn

Create a virtual environment owned by the application user:

Bash
sudo -u djangoapp python3 -m venv /srv/mysite/venv

Upgrade pip inside the virtual environment, not the system Python:

Bash
sudo -u djangoapp /srv/mysite/venv/bin/python -m pip install --upgrade pip

For this demo, install Django and Gunicorn:

Bash
sudo -u djangoapp /srv/mysite/venv/bin/python -m pip install django gunicorn

For an existing application, install its reviewed dependency file instead of blindly replacing versions:

Bash
sudo -u djangoapp /srv/mysite/venv/bin/python -m pip install -r /srv/mysite/app/requirements.txt

Create a demo project:

Bash
cd /srv/mysite/app sudo -u djangoapp /srv/mysite/venv/bin/django-admin startproject config .

Add a small health endpoint to config/urls.py:

Python
from django.contrib import admin from django.http import JsonResponse from django.urls import path def health(_request): return JsonResponse({"status": "ok"}) urlpatterns = [ path("admin/", admin.site.urls), path("health/", health), ]

Confirm the packages and WSGI module import correctly:

Bash
sudo -u djangoapp /srv/mysite/venv/bin/python -c 'import django, gunicorn, config.wsgi; print(django.get_version())'

Verify: Django should print a version and the command should exit without an import error.

Step 3 — Store the Django Secret Outside the Project

Django's deployment checklist recommends keeping SECRET_KEY secret and out of source control. Create a root-managed environment file that the service user can read:

Bash
sudo install -m 640 -o root -g djangoapp /dev/null /etc/mysite.env

Generate a high-entropy secret without printing it to your terminal history:

Bash
sudo sh -c 'printf "DJANGO_SECRET_KEY=%s\n" "$(python3 -c "import secrets; print(secrets.token_urlsafe(50))")" > /etc/mysite.env' sudo chown root:djangoapp /etc/mysite.env sudo chmod 640 /etc/mysite.env

Confirm the service account can read the file without displaying the secret:

Bash
sudo -u djangoapp test -r /etc/mysite.env && echo readable

Do not commit /etc/mysite.env to Git or copy its value into the systemd unit.

Verify: The command should print readable, and stat -c '%U %G %a' /etc/mysite.env should show root djangoapp 640.

Step 4 — Configure Django for Production

Edit /srv/mysite/app/config/settings.py and add import os near the top if it is not already present. Use production settings like these:

Python
import os SECRET_KEY = os.environ["DJANGO_SECRET_KEY"] DEBUG = False ALLOWED_HOSTS = ["example.com", "www.example.com"] STATIC_URL = "static/" STATIC_ROOT = BASE_DIR / "staticfiles"

Do not use ALLOWED_HOSTS = ["*"] as a shortcut. Django recommends validating the expected hostnames in production.

For an existing project, also review database credentials, email settings, caches, uploaded media, logging, and any environment-specific settings. Database passwords should be protected like SECRET_KEY rather than committed to the repository.

Load the environment and run Django's basic system check:

Bash
sudo -u djangoapp bash -c ' set -a . /etc/mysite.env set +a cd /srv/mysite/app ../venv/bin/python manage.py check '

Verify: manage.py check should finish without configuration errors and DEBUG should be False in the production settings.

Step 5 — Run Migrations and Collect Django Static Files

Apply migrations and collect static assets under STATIC_ROOT:

Bash
sudo -u djangoapp bash -c ' set -a . /etc/mysite.env set +a cd /srv/mysite/app ../venv/bin/python manage.py migrate ../venv/bin/python manage.py collectstatic --noinput '

Django's production documentation expects static files to be collected and then served by a web server or another static-file service rather than by the development server.

Check that the directory exists and contains files:

Bash
sudo -u djangoapp find /srv/mysite/app/staticfiles -maxdepth 2 -type f | head

For a real application, back up the database before production migrations and use your application's tested release procedure instead of treating every migration as risk-free.

Verify: Migrations should complete successfully and staticfiles/ should contain collected assets.

Step 6 — Test Django with Gunicorn on Localhost

Before creating a service, test Gunicorn locally. Bind only to loopback so the raw WSGI server is not exposed publicly:

Bash
sudo -u djangoapp bash -c ' set -a . /etc/mysite.env set +a cd /srv/mysite/app ../venv/bin/gunicorn \ --bind 127.0.0.1:8000 \ --workers 2 \ config.wsgi:application '

In a second SSH session, send the expected host header:

Bash
curl -H 'Host: example.com' http://127.0.0.1:8000/health/

Expected output:

Json
{"status": "ok"}

Django's runserver is a development server; the reason to move to Gunicorn is not that runserver is always single-threaded, but that Django explicitly says it is not designed for production.

Stop the foreground Gunicorn test with Ctrl+C after verification.

Verify: Gunicorn should return the health response on 127.0.0.1:8000, and no public firewall rule should exist for port 8000.

Step 7 — Run Gunicorn as a systemd Service over a Unix Socket

Create /etc/systemd/system/mysite-gunicorn.service:

Ini
[Unit] Description=Gunicorn for Django mysite After=network.target [Service] Type=notify NotifyAccess=main User=djangoapp Group=www-data WorkingDirectory=/srv/mysite/app EnvironmentFile=/etc/mysite.env RuntimeDirectory=mysite RuntimeDirectoryMode=0750 UMask=0007 ExecStart=/srv/mysite/venv/bin/gunicorn \ --workers 2 \ --access-logfile - \ --error-logfile - \ --bind unix:/run/mysite/gunicorn.sock \ config.wsgi:application ExecReload=/bin/kill -s HUP $MAINPID KillMode=mixed TimeoutStopSec=30 Restart=on-failure RestartSec=5 PrivateTmp=true NoNewPrivileges=true [Install] WantedBy=multi-user.target

Reload systemd and start the service:

Bash
sudo systemctl daemon-reload sudo systemctl enable --now mysite-gunicorn

Check the service and socket:

Bash
systemctl is-active mysite-gunicorn sudo ls -l /run/mysite/gunicorn.sock

Test the socket as the Nginx user:

Bash
sudo -u www-data curl \ --unix-socket /run/mysite/gunicorn.sock \ -H 'Host: example.com' \ http://localhost/health/

Gunicorn's current deployment documentation supports systemd-managed services and Unix sockets. Type=notify lets Gunicorn report readiness to systemd.

Verify: The service should be active, the socket should exist under /run/mysite/, and the www-data curl command should return {"status": "ok"}.

Step 8 — Configure Nginx for Django and Gunicorn

Create /etc/nginx/sites-available/mysite:

Nginx
server { listen 80; listen [::]:80; server_name example.com www.example.com; client_max_body_size 10m; location /static/ { alias /srv/mysite/app/staticfiles/; access_log off; expires 7d; add_header Cache-Control "public"; } location / { proxy_pass http://unix:/run/mysite/gunicorn.sock; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_redirect off; } }

This tutorial does not add WebSocket upgrade headers because standard Django through Gunicorn's WSGI worker is an HTTP WSGI deployment. If your application requires WebSockets or other ASGI behavior, use an ASGI deployment rather than copying WSGI settings blindly.

Enable the site and remove the Ubuntu default only if it is not serving anything else:

Bash
sudo ln -sfn /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/mysite sudo rm -f /etc/nginx/sites-enabled/default sudo nginx -t sudo systemctl reload nginx

On a dedicated single-site VM, you can also configure a separate default server that rejects unknown hostnames instead of forwarding them to Django.

Verify: sudo nginx -t should succeed and Nginx should reload without errors.

Step 9 — Set Static-File Permissions and Keep Gunicorn Private

Nginx needs read and traverse permission for the collected static directory, but it does not need write access to your project:

Bash
sudo chmod 755 /srv/mysite /srv/mysite/app sudo find /srv/mysite/app/staticfiles -type d -exec chmod 755 {} + sudo find /srv/mysite/app/staticfiles -type f -exec chmod 644 {} +

If UFW is active, allow SSH before making firewall changes, then allow Nginx:

Bash
sudo ufw allow OpenSSH sudo ufw allow 'Nginx Full' sudo ufw status numbered

Do not add a public rule for port 8000. The persistent Gunicorn service uses a Unix socket and Nginx is the public edge.

If your project has user-uploaded media, treat uploads as untrusted data and configure a separate media path carefully. Do not let Nginx execute uploaded content.

Verify: UFW should allow the intended SSH and web ports, and there should be no public Gunicorn port.

Step 10 — Verify Django, Gunicorn, Nginx, and Static Files End to End

Test the application through Nginx:

Bash
curl -H 'Host: example.com' http://127.0.0.1/health/ curl http://example.com/health/

Expected application response:

Json
{"status": "ok"}

Confirm an admin static file is served by Nginx:

Bash
curl -I http://example.com/static/admin/css/base.css

Check the two services:

Bash
systemctl is-active mysite-gunicorn nginx

Inspect recent logs if a request fails:

Bash
sudo journalctl -u mysite-gunicorn -n 50 --no-pager sudo tail -n 50 /var/log/nginx/error.log

Verify: The public health endpoint should succeed, the static file should return a successful HTTP response, and both services should be active.

Step 11 — Tune Gunicorn Workers from Measurements, Not a Fixed Formula

Gunicorn documents (2 × CPU cores) + 1 as a starting point, not a universal production rule. Too many workers can waste memory, increase database connections, and reduce throughput.

This tutorial starts with two workers on the existing 2 vCPU test profile. Measure before changing it:

Bash
ps -o pid,ppid,rss,%cpu,cmd -C gunicorn free -h uptime

Also watch:

  • request latency and error rate;
  • worker memory after normal traffic;
  • database connection usage;
  • CPU saturation;
  • timeout and restart events.

If you change --workers, reload the unit definition and restart during a controlled deployment:

Bash
sudo systemctl daemon-reload sudo systemctl restart mysite-gunicorn

For application-code deployments that are safe to reload, the unit also supports Gunicorn's HUP reload path:

Bash
sudo systemctl reload mysite-gunicorn

Do not use a long --timeout to hide slow views. Fix slow database queries, external calls, or background jobs according to the workload.

Verify: Worker count should fit available memory and database capacity without repeated OOM events, timeouts, or restarts.

Step 12 — Add HTTPS and Enable Django's HTTPS Security Settings

Before serving logins, admin sessions, password resets, or other sensitive traffic, enable site-wide HTTPS. Complete Install Certbot for Nginx on Ubuntu 24.04 with Let's Encrypt for certificate issuance and renewal testing.

Because Nginx is the trusted proxy and this configuration explicitly sets X-Forwarded-Proto, add these settings after HTTPS is working:

Python
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True

Treat HSTS separately. After HTTPS and renewal are stable, start with a short test value before increasing it:

Python
SECURE_HSTS_SECONDS = 300

Do not enable SECURE_PROXY_SSL_HEADER when requests can bypass your trusted proxy or when an untrusted client can control the forwarded-protocol header.

Run Django's deployment checks against the production environment:

Bash
sudo -u djangoapp bash -c ' set -a . /etc/mysite.env set +a cd /srv/mysite/app ../venv/bin/python manage.py check --deploy '

Review every warning rather than assuming one generic configuration is correct for every application.

Verify: HTTPS should work, HTTP should redirect to HTTPS, secure cookies should be enabled, and check --deploy warnings should be understood and resolved where applicable.

Step 13 — Test Reboot Persistence and the Final Production Path

Reboot during a safe test window:

Bash
sudo reboot

After reconnecting, check services:

Bash
systemctl is-active mysite-gunicorn nginx

Run the public checks:

Bash
curl -I https://example.com/ curl https://example.com/health/ curl -I https://example.com/static/admin/css/base.css

Confirm the Gunicorn socket exists again:

Bash
sudo ls -l /run/mysite/gunicorn.sock

The intended request path is:

Text
Browser → Nginx on 80/443 → Unix socket /run/mysite/gunicorn.sock → Gunicorn workers → Django WSGI application

Verify: Nginx and Gunicorn should start automatically, HTTPS should respond, static files should load, and the health endpoint should return {"status": "ok"} after reboot.

Step 14 — Operate, Update, and Clean Up Safely

Follow Gunicorn logs with journald:

Bash
sudo journalctl -u mysite-gunicorn -f

Validate Nginx before every reload:

Bash
sudo nginx -t && sudo systemctl reload nginx

Before dependency upgrades, review release notes and test the new environment. Do not run a blanket production pip install --upgrade without a tested dependency strategy.

To stop the application without deleting data:

Bash
sudo systemctl disable --now mysite-gunicorn

Disable the Nginx site if this hostname is being decommissioned:

Bash
sudo rm -f /etc/nginx/sites-enabled/mysite sudo nginx -t sudo systemctl reload nginx

Only after backups and decommissioning are confirmed should you remove /srv/mysite, /etc/mysite.env, or the systemd unit. If the application uses a production database or uploaded media, back those up separately before removal.

Verify: A stopped deployment should no longer serve the Django application, while unrelated Nginx sites and services should continue to work.

Conclusion

You deployed Django with Gunicorn and Nginx on Ubuntu 24.04 using a non-root service account, a Python virtual environment, a protected environment file, a systemd-managed Unix socket, collected static files, Nginx reverse proxying, HTTPS-aware Django settings, deployment checks, and reboot verification.

The important production decisions are not a magic worker count or a synthetic requests-per-second number. Keep secrets out of source control, keep Gunicorn private, let Nginx own the public edge, tune workers from real CPU/memory/database behavior, and run manage.py check --deploy against your actual production settings.

For related setup work, see Install pip on Ubuntu 24.04 and Install Nginx on Ubuntu 24.04. The detailed HTTPS procedure is linked in Step 12. For the full deployment lifecycle, read Application Deployment on a Linux VM.

Deploy a Raff Ubuntu VM for Django, Gunicorn, and Nginx. Verify HTTPS, service recovery, and database capacity before accepting production traffic.

Tested on 2 vCPU and 4 GB RAM: $17.99 a month · 14-day money-back guarantee

Deploy Your Server
Was this article helpful?
Aybars Altınyay
Aybars Altınyay
Platform Engineer & Technical Writer

Aybars is a Platform Engineer & Technical Writer at Raff Technologies. He works on Linux VM templates, self-hosted application workflows, and security-focused deployment validation, turning tested infrastructure procedures into clear, practical tutorials for developers and teams.

Launch your Django app on your own Ubuntu 24.04 server.

Tested on 2 vCPU and 4 GB RAM: $17.99 a month

Ubuntu, Debian and other Linux distributions with full root and SSH access, up and running in about 55 seconds.

14-day money-back guarantee

Frequently asked questions

Can I use Django with Gunicorn?
Yes. Django exposes a WSGI application that Gunicorn can run directly, for example `gunicorn config.wsgi:application`. Django's production documentation lists Gunicorn as a supported WSGI deployment option.
Can I use Gunicorn with Nginx?
Yes. Gunicorn recommends running behind a proxy server, and Nginx is a common choice. Nginx accepts public HTTP/HTTPS traffic and proxies application requests to a private Gunicorn socket or localhost port.
Can I use Nginx with Django?
Yes. Nginx can serve collected Django static files, terminate TLS, validate the public hostname, and proxy dynamic requests to Gunicorn while Django remains behind the proxy.
How many Gunicorn workers should Django use?
Gunicorn documents `(2 × CPU cores) + 1` as a starting point, not a rule. Start conservatively and tune from CPU, memory, database connections, latency, and error rate under representative load.
Should Gunicorn listen on 0.0.0.0 in production?
Usually not when Nginx runs on the same VM. Bind Gunicorn to localhost or a Unix socket and expose only Nginx on ports 80 and 443.
Does Gunicorn serve Django static files?
Gunicorn should handle application requests, not act as the production static-file server. Run `collectstatic` and serve `STATIC_ROOT` with Nginx, a CDN, or another dedicated static-file service.
Should I store DJANGO_SECRET_KEY in the systemd service file?
Avoid hardcoding the production secret in source code or a broadly readable unit file. Load it from a protected environment file or another secret-management mechanism and restrict access to the service account.
Do I need Gunicorn for async Django or WebSockets?
This tutorial uses Django's WSGI interface. Applications that require WebSockets or significant ASGI behavior should use an ASGI deployment and choose an ASGI-capable server rather than copying a WSGI Gunicorn configuration.

Related Articles

View all →