Skip to content

Deploying Python apps with Gunicorn and systemd

Run a Django or Flask app under Gunicorn with sync or gthread workers, expose it on a UNIX socket, and put systemd in charge of the lifecycle.

Gunicorn is the WSGI server most Python web teams deploy because it understands forks, signals, and graceful reload. Behind Nginx, gunicorn handles the request-response cycle and the OS handles process supervision. This article wires a Django or Flask app into Gunicorn served over a UNIX socket, with the worker class and count actually tuned to the workload.

How to verify

Look at the current state of the WSGI tier:

systemctl status gunicorn-app --no-pager | head
ls -la /run/gunicorn-app.sock 2>/dev/null
sudo ss -lxn | grep gunicorn
curl --unix-socket /run/gunicorn-app.sock http://localhost/ -I
ps -eo pid,ppid,etime,cmd | grep -E "gunicorn|wsgi" | head

If a socket exists but curl returns 502 or hangs, the master is up but workers crashed at import time. journalctl -u gunicorn-app -n 200 will show the traceback.

What’s happening

Gunicorn is a pre-fork worker model. A master process binds the socket and forks N worker processes; each worker accepts a connection, runs the WSGI callable, returns the response, accepts the next connection. Workers do not share memory after the fork (copy-on-write) and they do not share Python objects safely — each one is a self-contained interpreter.

The worker class decides what concurrency model lives inside that interpreter. sync is one request at a time per worker, simplest, safe for any code. gthread adds N threads per worker so a single worker can handle multiple slow requests when much of the time is spent in I/O. gevent and uvicorn.workers.UvicornWorker (for ASGI) are alternatives for very different shapes of workload. The defaults bite: sync with two workers handles only two concurrent requests, full stop.

The other half of the design is the listening socket. A UNIX socket under /run/ is faster than TCP on localhost, cleaner for permissions, and lets Nginx avoid an ephemeral port allocation per connection.

The procedure

  1. Install Gunicorn into the project venv (assuming /opt/venvs/app exists from the Python install article):

    sudo -iu deploy
    /opt/venvs/app/bin/pip install gunicorn
    /opt/venvs/app/bin/gunicorn --version
  2. Pick worker count and class. The standard formula is 2 × CPU + 1 for sync. For mixed I/O workloads use gthread with 4-8 threads per worker:

    # 4-core host, mostly DB-bound
    /opt/venvs/app/bin/gunicorn app.wsgi:application \
      --workers 5 --threads 4 --worker-class gthread \
      --bind unix:/run/gunicorn-app.sock
  3. Drop a config file so the systemd unit stays short. /etc/gunicorn/app.conf.py:

    bind = "unix:/run/gunicorn-app.sock"
    workers = 5
    threads = 4
    worker_class = "gthread"
    timeout = 60
    graceful_timeout = 30
    keepalive = 5
    max_requests = 1000
    max_requests_jitter = 100
    accesslog = "-"
    errorlog = "-"

    max_requests recycles workers periodically — bounds the impact of any slow leak.

  4. Create the systemd unit at /etc/systemd/system/gunicorn-app.service:

    [Unit]
    Description=Gunicorn for app
    After=network.target
    
    [Service]
    User=deploy
    Group=www-data
    WorkingDirectory=/var/www/app
    RuntimeDirectory=gunicorn-app
    RuntimeDirectoryMode=0750
    Environment=DJANGO_SETTINGS_MODULE=app.settings.prod
    ExecStart=/opt/venvs/app/bin/gunicorn -c /etc/gunicorn/app.conf.py app.wsgi:application
    ExecReload=/bin/kill -s HUP $MAINPID
    KillMode=mixed
    Restart=on-failure
    
    [Install]
    WantedBy=multi-user.target

    Group=www-data and RuntimeDirectoryMode=0750 together let Nginx (running as www-data) connect to the socket without making it world-readable.

  5. Reload, enable, start, point Nginx at the socket:

    sudo systemctl daemon-reload
    sudo systemctl enable --now gunicorn-app
    journalctl -u gunicorn-app -n 50 --no-pager

    In the Nginx server block, the upstream is proxy_pass http://unix:/run/gunicorn-app.sock;.

Operational notes

  • --preload saves memory by loading the app in the master before forking, but it breaks any code that opens DB connections at import time (the master’s connection is inherited by each worker — connection pool corruption follows). Use --preload only after auditing your imports.
  • timeout 60 means Gunicorn kills any worker stuck in a single request for 60 seconds. A Django view that calls a slow external API will be killed mid-request. Either raise the timeout or move slow work to a queue.
  • gthread does not give you parallelism for CPU-bound code — the GIL still serializes it. Use it for I/O-bound work only; for CPU-bound, use more sync workers.
  • Logging to stdout/stderr (accesslog = "-") lets journald capture and rotate everything for free. If you write to a file path, set up logrotate or the disk fills.
  • For graceful deploys, systemctl reload gunicorn-app sends SIGHUP, which forks new workers before killing old ones — zero-downtime if the app boots in under graceful_timeout.

If the workload is ASGI (FastAPI, Django Channels), swap the worker class to uvicorn.workers.UvicornWorker and the same systemd shape applies. Stack Harbor’s managed operations practice runs Gunicorn-on-systemd as the default for synchronous Python web apps, with Nginx out front and the socket living in /run/ — see Nginx as a reverse proxy for the matching front-end.