Web frameworks · Advanced · 28 min
How to Deploy a Django App with Gunicorn and Nginx on Ubuntu 26.04
By Padding · Updated 15 Nov 2026
Ubuntu 26.04.1 LTS · Django 6.1 · Gunicorn 27 · Nginx 1.30
You will run a Django 6.1 project on Ubuntu 26.04 with DEBUG off, a secret key kept in a private file, Gunicorn started by a systemd socket and service as an unprivileged user, and Nginx serving static files and passing everything else to the app.
On this page
Django's own development server is for development only. On a production server, the usual stack has three parts. Nginx faces the internet, serves static files and handles slow clients. Gunicorn runs your Python code in several worker processes. systemd starts Gunicorn at boot, restarts it if it dies, and keeps it running as a user with no other power.
This tutorial sets that stack up from an empty server, with the settings a public Django site must have: DEBUG off, the secret key outside the code, and the allowed host names listed. It uses a small throwaway project, mysite, so every step is complete. For your own project you change the paths and the project name. Nginx is not installed here: follow the Nginx install tutorial first.
The project uses SQLite, a single file, which suits a small site and keeps this tutorial short. For a larger site, use PostgreSQL, as in the PostgreSQL 18 tutorial. The Python is the Python 3.14 that Ubuntu 26.04 ships, and Django 6.1 supports Python 3.12 to 3.15 (its release notes and PyPI classifiers).
Step 1 · Install the packages and create an unprivileged user
Install Python with its virtual environment support, and curl for the checks at the end:
sudo apt update
sudo apt install -y python3 python3-venv curlThe app will run as its own system user, django. That user has no password, no login shell and no home folder of its own, so a flaw in the app cannot be turned into a login on the server:
sudo useradd --system --user-group --no-create-home --home-dir /srv/mysite --shell /usr/sbin/nologin djangoNow create the folders. The code is owned by root, so the app cannot change its own source. The app may write to only two places: its database folder and its collected static files:
sudo install -d -m 755 /srv/mysite /srv/mysite/app
sudo install -d -o django -g django -m 750 /var/lib/mysite
sudo install -d -o django -g django -m 755 /var/www/mysite /var/www/mysite/static
sudo install -d -o root -g django -m 750 /etc/mysiteCheck it worked
id django
ls -ld /srv/mysite /var/lib/mysite /var/www/mysite/static /etc/mysiteid django shows a user and a group named django. The ls lines show owners and modes: /srv/mysite owned by root, /var/lib/mysite owned by django with drwxr-x---, and /etc/mysite owned by root with group django.
Step 2 · Install Django and Gunicorn in a virtual environment
Create the environment inside /srv/mysite, and install both packages. They go in as root, so the app user can run them but not modify them. Pin Gunicorn to a version you have tested, and keep Django within the 6.1 series:
sudo python3 -m venv /srv/mysite/venv
sudo /srv/mysite/venv/bin/pip install "django>=6.1,<6.2" gunicorn==27.0.1Check it worked
/srv/mysite/venv/bin/django-admin --version
/srv/mysite/venv/bin/gunicorn --versionThe first prints 6.1. and a patch number, and the second prints gunicorn (version 27.0.1).
Step 3 · Create the project and configure it for production
Start a project in /srv/mysite/app. The name mysite is both the folder and the Python package. Gunicorn will load mysite.wsgi:application, the WSGI entry point Django creates:
cd /srv/mysite/app
sudo /srv/mysite/venv/bin/django-admin startproject mysite .Give the project a page to serve, apart from the admin, so you can check that the app answers. Replace mysite/urls.py:
sudo tee /srv/mysite/app/mysite/urls.py > /dev/null <<'PY'
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),
]
PYDjango generates settings.py for development: DEBUG = True, a throwaway secret key, and an empty list of allowed hosts. Add production settings at the end of the file. Later lines win, so they replace the generated values, and appending does not depend on the exact text Django wrote:
sudo tee -a /srv/mysite/app/mysite/settings.py > /dev/null <<'PY'
# Production settings
import os
DEBUG = False
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
ALLOWED_HOSTS = os.environ["DJANGO_ALLOWED_HOSTS"].split(",")
STATIC_ROOT = "/var/www/mysite/static"
DATABASES["default"]["NAME"] = "/var/lib/mysite/db.sqlite3"
MAILERS = {
"default": {
"BACKEND": "django.core.mail.backends.smtp.EmailBackend",
"OPTIONS": {"host": "localhost"},
},
}
PYWhat each line does. DEBUG = False stops Django showing code, settings and tracebacks to visitors, which it does when DEBUG is on. The secret key and the allowed hosts come from environment variables, so they are not in the code or in Git. Django refuses requests whose Host header is not in ALLOWED_HOSTS, which blocks host header attacks. STATIC_ROOT is where collectstatic gathers files for Nginx. The DATABASES line moves the SQLite file to the folder the app user owns. MAILERS is Django 6.1's email setting. A new project prints email to the console, and Django's deployment check refuses that backend in production. This version sends through an SMTP server on the same machine. Point host at your own mail service, and read any username and password from the environment file, never from the code.
Step 4 · Keep the secrets in a private file
Create the environment file with its permissions first, empty, so the secret is never in a readable file, even for a moment. Root owns it, the group django can read it, and nobody else can:
sudo install -m 640 -o root -g django /dev/null /etc/mysite/envGenerate a secret key and append it. The key travels through a pipe, so it does not appear on a command line or in your shell history. Then add the host names. Replace the example names with your own domain, or your server's IP address:
python3 -c 'import secrets; print("DJANGO_SECRET_KEY=" + secrets.token_urlsafe(50))' | sudo tee -a /etc/mysite/env > /dev/null
echo 'DJANGO_ALLOWED_HOSTS=example.com,www.example.com' | sudo tee -a /etc/mysite/env > /dev/null
sudo ls -l /etc/mysite/env
sudo grep -c '^DJANGO_SECRET_KEY=' /etc/mysite/envCheck it worked
The ls line starts with -rw-r----- and shows owner root and group django. The grep prints 1, which proves the key is there without printing it. If you change the secret key later, every logged-in user is signed out, and password reset links stop working.
Step 5 · Run Django's setup commands as the app user
Django's management commands need the same environment variables as the running app. A small wrapper script loads the file and runs manage.py, so you run each command the same way:
sudo install -m 755 /dev/null /srv/mysite/manage
sudo tee /srv/mysite/manage > /dev/null <<'SH'
#!/bin/sh
set -a
. /etc/mysite/env
set +a
exec /srv/mysite/venv/bin/python /srv/mysite/app/manage.py "$@"
SHRun the three commands every deploy needs, as the django user. migrate creates the database tables, collectstatic copies static files to STATIC_ROOT, and check --deploy lists production settings you have not made yet:
sudo -u django /srv/mysite/manage migrate
sudo -u django /srv/mysite/manage collectstatic --noinput
sudo -u django /srv/mysite/manage check --deployCheck it worked
migrate ends with Applying sessions.0001_initial... OK. collectstatic reports that some number of static files were copied to /var/www/mysite/static. check --deploy prints four warnings, because the site is not on HTTPS yet. Expect advice about SECURE_HSTS_SECONDS, SECURE_SSL_REDIRECT, SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE. Those four settings only make sense once the site is served over HTTPS, and the last step of this tutorial points you to them. It reports nothing about DEBUG, the SECRET_KEY or the email setting.
Create an administrator when you want one, with sudo -u django /srv/mysite/manage createsuperuser. It prompts for a password, so the password never appears on a command line.
Step 6 · Run Gunicorn under systemd
Gunicorn serves the app on a UNIX socket, a file that stands in for a network port, which Nginx connects to. systemd creates the socket and starts Gunicorn when the first request arrives. This is called socket activation, and it means that Nginx can start before the app does and requests wait instead of failing. The socket is shared with Nginx through a group. The Nginx package from nginx.org runs its workers as the user nginx, which is what the units below assume. Nginx from Ubuntu's own archive runs as www-data, and you would use that name instead. Create the socket unit, which makes the socket owned by root and readable by the nginx group only:
# /etc/systemd/system/mysite.socket
[Unit]
Description=Gunicorn socket for mysite
[Socket]
ListenStream=/run/mysite.sock
SocketUser=root
SocketGroup=nginx
SocketMode=0660
[Install]
WantedBy=sockets.targetThe service unit says how to run Gunicorn. It runs as the django user, reads its secrets from the environment file, and is told to expect the socket from systemd, because it has no --bind option:
# /etc/systemd/system/mysite.service
[Unit]
Description=Gunicorn for mysite
Requires=mysite.socket
After=network.target
[Service]
Type=notify
NotifyAccess=main
User=django
Group=django
WorkingDirectory=/srv/mysite/app
EnvironmentFile=/etc/mysite/env
ExecStart=/srv/mysite/venv/bin/gunicorn --workers 3 mysite.wsgi:application
ExecReload=/bin/kill -s HUP $MAINPID
KillMode=mixed
TimeoutStopSec=5
PrivateTmp=true
[Install]
WantedBy=multi-user.targetBoth units follow the examples in the Gunicorn deployment guide. --workers 3 is a starting point. A common rule is two times the number of CPU cores plus one, as long as memory allows. Write each unit with sudo nano or sudo tee as in the systemd service tutorial, then enable the socket. The service itself starts on the first request:
sudo systemctl daemon-reload
sudo systemctl enable --now mysite.socketTest the socket from the nginx user, which is the one that will use it. This also proves that the permissions are right, and that Gunicorn starts:
sudo -u nginx curl --unix-socket /run/mysite.sock -H 'Host: example.com' http://localhost/health/
sudo systemctl status mysite.service --no-pagerThe curl command prints {"status": "ok"}, and the status shows the service as active (running) with a master process and three workers.
Troubleshooting
If the test prints 502 or Permission denied, check the socket's owner and mode with ls -l /run/mysite.sock: it must be group nginx with rw for the group. If the service fails, read why with journalctl -u mysite.service -n 50 --no-pager. A KeyError: 'DJANGO_SECRET_KEY' means the environment file is missing the key or the EnvironmentFile path is wrong, and a Permission denied on the database folder means /var/lib/mysite is not owned by django.
Step 7 · Configure Nginx
Nginx serves the static files straight from disk, which is much faster than going through Python, and passes everything else to Gunicorn. The nginx.org package reads site files from /etc/nginx/conf.d/. Create mysite.conf, with your own domain in server_name:
sudo tee /etc/nginx/conf.d/mysite.conf > /dev/null <<'NGINX'
upstream mysite_app {
server unix:/run/mysite.sock fail_timeout=0;
}
server {
listen 80;
server_name example.com www.example.com;
location /static/ {
alias /var/www/mysite/static/;
expires 30d;
}
location / {
proxy_set_header Host $http_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;
proxy_pass http://mysite_app;
}
}
NGINX
sudo nginx -tfail_timeout=0 makes Nginx retry a socket at once if Gunicorn restarted. X-Forwarded-For and X-Forwarded-Proto tell Django the visitor's address and whether the request was HTTPS. The request does not look like HTTPS to Django until you add the setting at the end of this tutorial. The default site that came with the nginx.org package listens on the same port with the name localhost. Your server_name matches requests for your domain first, so you can leave it, and remove /etc/nginx/conf.d/default.conf once your site works.
nginx -t must print syntax is ok and test is successful. Then apply the change without dropping connections:
sudo systemctl reload nginxStep 8 · Check the whole stack
Request the pages through Nginx on port 80. The Host header stands in for the domain until DNS points at the server. Use your own domain, or leave out -H and use the server's address in ALLOWED_HOSTS:
curl -i -H 'Host: example.com' http://127.0.0.1/health/
curl -s -o /dev/null -w 'admin login: %{http_code}\n' -H 'Host: example.com' http://127.0.0.1/admin/login/
curl -sI -H 'Host: example.com' http://127.0.0.1/static/admin/css/base.cssThe first shows HTTP/1.1 200 OK and the body {"status": "ok"}, with a Server: nginx header. The second prints admin login: 200. The third shows 200 and a Content-Type: text/css header, served by Nginx from the static folder without touching Python.
Now check that the production settings work. A page that does not exist must show a plain error, not Django's debug page with its list of URL patterns. A host name that is not allowed must be refused:
curl -s -H 'Host: example.com' http://127.0.0.1/nothing-here/ | head -n 5
sudo curl -s -o /dev/null -w 'wrong host: %{http_code}\n' --unix-socket /run/mysite.sock -H 'Host: other.test' http://localhost/health/The first prints a short HTML page with Not Found and nothing about URL patterns. The second sends a request with a host name that is not in ALLOWED_HOSTS straight to Gunicorn's socket, and prints wrong host: 400. Through Nginx, a name that does not match any server_name is answered by the default site and never reaches Django, so you test it on the socket.
Step 9 · Deploy changes, and turn on HTTPS
To ship new code, replace the files under /srv/mysite/app, run migrate and collectstatic again as the django user, and tell Gunicorn to reload its workers without dropping requests:
sudo systemctl reload mysite.serviceLogs are in the journal: journalctl -u mysite.service for the app and /var/log/nginx/error.log for Nginx. A public site needs HTTPS. Follow the Let's Encrypt and Nginx tutorial, then add these settings to the end of settings.py, which clear the warnings from check --deploy:
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 3600
CSRF_TRUSTED_ORIGINS = ["https://example.com"]Start SECURE_HSTS_SECONDS small. Browsers remember the value, and a mistake with a long period locks visitors out. Raise it to a year when you are sure. Only set SECURE_PROXY_SSL_HEADER when Nginx always sets X-Forwarded-Proto itself, as in the file above, since otherwise a client could fake it.
Step 10 · Remove it
This step deletes the demo project, its database and its secret key, and cannot be undone. Stop and remove the systemd units first:
sudo systemctl disable --now mysite.socket mysite.service
sudo rm /etc/systemd/system/mysite.socket /etc/systemd/system/mysite.service
sudo systemctl daemon-reloadThen remove the Nginx site, the files and the user, and check that Nginx is still happy without the deleted file:
sudo rm /etc/nginx/conf.d/mysite.conf
sudo rm -rf /srv/mysite /var/lib/mysite /var/www/mysite /etc/mysite
sudo userdel django
sudo nginx -tOnly now reload Nginx, so it stops serving the site:
sudo systemctl reload nginxCheck it worked
id django reports that the user does not exist, ls /srv/mysite reports no such file or directory, and nginx -t printed test is successful.
Next steps
- Add HTTPS: free HTTPS with Let's Encrypt and Nginx.
- Learn how systemd units work in detail: run an app as a systemd service.
- Add security headers: add security headers in Nginx.
- Move the database to a server: install PostgreSQL 18 on Ubuntu 26.04.
Related tutorials
- How to Install Nginx on Ubuntu 26.04You will install the current stable Nginx 1.30 from the official nginx.org repository on Ubuntu 26.04, serve its test page, and learn where its files live and how to reload it safely.
- How to Run Your App as a systemd Service on Ubuntu 26.04You will write a systemd unit file that starts your app at boot, restarts it when it crashes, runs it as an unprivileged user, and sends its logs to the journal.
- How to Create Your First Django 6 AppYou will create a Django 6.1 project with uv on Python 3.15, build a small bookmarks app with a database model, an admin screen, a page and a test, and see how the pieces connect.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials