Skip to main content

Backend Development

Build a Django Task Tracker, Part 4: Deploy with Gunicorn and Caddy

Move from a development server to an HTTPS deployment with environment settings, systemd, and operational checks.

A working development server is a checkpoint, not a deployment. This chapter runs the same task tracker with Gunicorn behind Caddy and uses systemd to keep the application running. The commands assume a Linux server with systemd, Python 3.12+, and Caddy installed. You also need a domain whose DNS points to that server and permission to configure its services.

Use a separate hostname and directory for this tutorial. Do not replace the live CodeEasy service or reuse its database. The example names below are placeholders to adapt: project directory /opt/apps/task-tracker, service user ubuntu, and domain tasks.example.com.

Prepare a clean installation

Extract the source archive into /opt/apps/task-tracker. Ensure the service user owns the project and can write the directory containing the SQLite database. Create a virtual environment and install the example requirements there:

cd /opt/apps/task-tracker
python3 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt

Create /etc/task-tracker.env using an editor. Keep it readable only by root and the intended deployment operator. systemd reads the environment file before starting the process. It is not a file to commit or include in a source archive.

DJANGO_DEBUG=false
DJANGO_SECRET_KEY=REPLACE_WITH_A_LONG_RANDOM_VALUE
DJANGO_ALLOWED_HOSTS=tasks.example.com
DJANGO_DB_PATH=/opt/apps/task-tracker/db.sqlite3

Generate a fresh random secret, for example with Python's secrets.token_urlsafe(48), and insert the result. Do not use the displayed placeholder. The settings reject the local default key when debug is disabled. An environment variable is not automatically loaded by an interactive shell: export the same four values in your deployment shell before running management commands. Avoid posting their values in logs or support messages.

Understand the production settings

The downloadable settings file shows the full configuration:

config/settings.py

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = os.environ.get('DJANGO_DEBUG', 'true').lower() == 'true'
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'local-tutorial-key-do-not-deploy')
if not DEBUG and SECRET_KEY == 'local-tutorial-key-do-not-deploy':
    raise RuntimeError('Set DJANGO_SECRET_KEY before deploying.')
ALLOWED_HOSTS = [host.strip() for host in os.environ.get('DJANGO_ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',') if host.strip()]
INSTALLED_APPS = [
    'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes',
    'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tasks',
]
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'config.urls'
WSGI_APPLICATION = 'config.wsgi.application'
TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True,
              'OPTIONS': {'context_processors': ['django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages']}}]
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.environ.get('DJANGO_DB_PATH', str(BASE_DIR / 'db.sqlite3'))}}
AUTH_PASSWORD_VALIDATORS = [
    {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
    {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'},
    {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
    {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
TIME_ZONE = 'UTC'
USE_TZ = True
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/accounts/login/'
SESSION_COOKIE_SECURE = not DEBUG
CSRF_COOKIE_SECURE = not DEBUG
SECURE_SSL_REDIRECT = not DEBUG
# Use only behind the documented trusted Caddy proxy bound to loopback.
if not DEBUG:
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

The application switches on secure cookies and HTTPS redirects when debug is false. Caddy terminates HTTPS and forwards a scheme header; Django trusts that header only in the documented topology, where Gunicorn binds to loopback and the trusted proxy overwrites it. A publicly reachable Gunicorn socket or an untrusted proxy would require another trust assessment.

ALLOWED_HOSTS contains hostnames, not https:// URLs. Django's same-origin CSRF checks should work when Caddy preserves the correct host and scheme. If you receive a CSRF error, inspect those values and the secure-cookie behavior rather than disabling the middleware or adding a wildcard trusted origin.

Apply migrations with the intended environment

With the production variables exported in your shell:

.venv/bin/python manage.py check --deploy
.venv/bin/python manage.py migrate
.venv/bin/python manage.py collectstatic --noinput
.venv/bin/python manage.py createsuperuser

Review warnings from check --deploy. HSTS is intentionally not enabled by this example: enable it only after verifying your HTTPS and subdomain policy. Other warnings may require decisions specific to your setup. The superuser is for initial administration; create ordinary users for daily use.

SQLite keeps this example easy to inspect. Back it up using SQLite's backup facilities and test restoration to another database file. Blindly copying a database during writes can miss journal state. For higher write concurrency or multiple application hosts, plan and test a database service such as PostgreSQL rather than assuming this setup scales unchanged.

Keep Gunicorn under systemd

Create /etc/systemd/system/task-tracker.service:

[Unit]
Description=Django tutorial task tracker
After=network.target

[Service]
User=ubuntu
WorkingDirectory=/opt/apps/task-tracker
EnvironmentFile=/etc/task-tracker.env
ExecStart=/opt/apps/task-tracker/.venv/bin/gunicorn --workers 2 --bind 127.0.0.1:8010 config.wsgi:application
Restart=on-failure

[Install]
WantedBy=multi-user.target

Adapt the user and paths to your machine. The working directory lets the process import config, while the absolute executable selects the correct virtual environment. Port 8010 is a sample choice; confirm it is free. Keep it on loopback.

Add a dedicated block to your Caddy configuration:

 tasks.example.com {
    handle_path /static/* {
        root * /opt/apps/task-tracker/staticfiles
        file_server
    }
    handle {
        reverse_proxy 127.0.0.1:8010
    }
}

The reverse proxy handles dynamic requests, while Caddy serves collected admin assets. Check filesystem permissions for Caddy's user. Only expose ports needed for SSH and HTTP/HTTPS through your server and cloud firewalls; Caddy also needs the network access required for certificate issuance.

Validate the full proxy configuration before reloading it, then start the service:

sudo caddy validate --config /etc/caddy/Caddyfile
sudo systemctl daemon-reload
sudo systemctl enable --now task-tracker
sudo systemctl reload caddy

Verify the result and diagnose failures

Open the HTTPS login page, add a task, mark it complete, reload, and sign out. Test a second ordinary account to confirm isolation. Check that /static/admin/css/base.css returns CSS. An HTTP request should redirect to HTTPS; a normal HTTPS request should not loop.

For a 502, inspect systemctl status task-tracker and journalctl -u task-tracker -n 50 --no-pager. Common causes are an incorrect virtualenv path, an occupied port, missing variables, or a failed import. For “unable to open database,” check both the file and parent-directory permissions. A migration error is different from a proxy failure; fix the layer that produced it.

This is a teaching deployment, not a managed hosting service. Before offering registration publicly, add login abuse protection, account recovery, monitoring, dependency maintenance, and a tested backup process. You now have a project you can explain from request to database to process manager. Compare your decisions with Django's deployment checklist, then choose a small feature and repeat the model → form → ownership → test cycle.

Stay curious

A new idea for your inbox.

Occasional updates when we publish new guides. No noise.

Subscribing...