The production-grade way to run a Flask or Django app is to let Gunicorn run the Python, let systemd keep Gunicorn alive, and let Nginx sit in front for TLS and static files — with Gunicorn listening on a Unix socket rather than a port. Nginx terminates HTTPS and proxies dynamic requests to unix:/run/gunicorn.sock; Gunicorn’s master process forks a fixed pool of workers, each running a copy of your WSGI callable; systemd starts the whole thing at boot, restarts it if it crashes, and reloads it without dropping a request. This guide wires those three pieces together and shows the exact command output that tells you each step worked.
What you’ll accomplish
- Run Gunicorn as a supervised systemd service that starts at boot and restarts on failure.
- Have Gunicorn listen on a Unix socket, and Nginx reverse-proxy to it with TLS and static files handled up front.
- Pick a worker count and worker class that match your CPU and your app’s I/O profile.
- Reload new code with zero dropped requests using a graceful SIGHUP.
- Diagnose the failures you will actually hit: 502s, worker timeouts, and import-path mistakes.
Prerequisites
- Python 3.11 or newer, with your app in a virtual environment. Anything from 3.11 through 3.13 works the same for this setup.
- A WSGI entry point: for Flask, an
appobject inapp.py(referenced asapp:app); for Django, the project’swsgi.py(referenced asmyproject.wsgi:application). - Nginx installed and running (
sudo apt install nginxon Debian and Ubuntu,sudo dnf install nginxon RHEL family). - A non-root system user to own and run the service. This guide uses
appuserand an app directory of/srv/myapp. Never run Gunicorn asroot. - Root or
sudofor the systemd and Nginx configuration. If you have not managed unit files before, the systemd service management guide covers the commands used here.
How it works
A browser opens an HTTPS connection to Nginx on port 443. Nginx does the two jobs it is best at: it terminates TLS, and it serves static assets directly off disk. Anything dynamic — a request that has to run your Python — it forwards over a Unix socket to Gunicorn. Gunicorn’s master process owns that socket and does no request work itself; it forks a fixed number of worker processes, hands each the same listening socket, and lets the kernel decide which idle worker accepts the next connection. Each worker imports your WSGI app once at startup and then serves requests from it.
The reason to use a Unix socket instead of a TCP port like 127.0.0.1:8000 is that the socket is a file in the filesystem. Traffic never touches the TCP stack, so there is no loopback network hop and no port to accidentally expose; access is controlled by ordinary file permissions, so only the user and group Nginx runs as can connect. A TCP bind works and is sometimes necessary — when Gunicorn and Nginx live on different hosts — but on a single box the socket is simpler and one less thing to firewall.
The worker count is the tuning decision that matters most. Gunicorn’s own guidance is (2 * CPU cores) + 1 as a starting point: enough workers that some can be blocked on I/O while others run on the CPU, without so many that they thrash. On a 2-core VM that is 5 workers. Each worker is a full process holding its own copy of your app in memory, so more workers cost more RAM. The default sync worker class handles one request at a time per worker and is the right choice for ordinary request/response apps. If your views spend most of their time waiting — calling slow upstream APIs, for instance — the gthread class runs several threads inside each worker so one blocked request does not tie up the whole process.
Step-by-step
1. Create the virtual environment and install Gunicorn. As appuser, from your app directory, build a venv and install Gunicorn alongside your app’s dependencies.
cd /srv/myapp
python3.11 -m venv venv
./venv/bin/pip install gunicorn flask # or: -r requirements.txt for a real app
./venv/bin/gunicorn --version
Expected output confirms the binary is in the venv:
gunicorn (version 23.0.0)
2. Test-run Gunicorn on a socket by hand. Before writing any unit file, prove the app boots and binds the socket. Run it in the foreground.
cd /srv/myapp
./venv/bin/gunicorn --workers 3 --bind unix:/run/gunicorn.sock app:app
You should see the master and workers come up, with no traceback:
[1] [INFO] Starting gunicorn 23.0.0
[1] [INFO] Listening at: unix:/run/gunicorn.sock (1)
[1] [INFO] Using worker: sync
[8] [INFO] Booting worker with pid: 8
If instead you get ModuleNotFoundError or Failed to find attribute 'app', the app:app reference is wrong — the part before the colon is the import path, the part after is the callable. Press Ctrl+C to stop, then fix it before continuing. For Django, the equivalent is myproject.wsgi:application.
3. Write the systemd socket unit. Letting systemd own the socket means the socket file exists with the right permissions before Gunicorn even starts, and systemd can hand it over cleanly. Create /etc/systemd/system/gunicorn.socket:
[Unit]
Description=gunicorn socket for myapp
[Socket]
ListenStream=/run/gunicorn.sock
SocketGroup=www-data
SocketMode=0660
[Install]
WantedBy=sockets.target
SocketGroup=www-data sets the socket’s owning group to the user Nginx runs as (www-data on Debian/Ubuntu; use nginx on the RHEL family), and mode 0660 lets that group connect while keeping everyone else out.
4. Write the systemd service unit. Create /etc/systemd/system/gunicorn.service. The key fields are WorkingDirectory (so the import path resolves), the absolute path to the venv’s Gunicorn in ExecStart, and ExecReload for graceful reloads.
[Unit]
Description=gunicorn daemon for myapp
Requires=gunicorn.socket
After=network.target
[Service]
User=appuser
Group=www-data
WorkingDirectory=/srv/myapp
ExecStart=/srv/myapp/venv/bin/gunicorn \
--workers 5 \
--worker-class sync \
--graceful-timeout 30 \
--timeout 60 \
--bind unix:/run/gunicorn.sock \
app:app
ExecReload=/bin/kill -s HUP $MAINPID
KillMode=mixed
Restart=on-failure
[Install]
WantedBy=multi-user.target
Group=www-data runs the workers under the group Nginx uses, so the socket is group-owned by www-data and Nginx can connect to it. --timeout 60 kills and replaces a worker that has been silent for 60 seconds; --graceful-timeout 30 gives a worker 30 seconds to finish in-flight requests during a reload before it is forced down.
5. Reload systemd, enable, and start. Pick up the new units, enable the socket so it opens at boot, and start the service.
sudo systemctl daemon-reload
sudo systemctl enable --now gunicorn.socket
sudo systemctl start gunicorn.service
sudo systemctl status gunicorn.service
A working service reads active (running) with the master and workers listed:
● gunicorn.service - gunicorn daemon for myapp
Active: active (running) since Mon 2026-07-20 09:14:02 UTC
Main PID: 4120 (gunicorn)
Tasks: 6 (limit: 4915)
6. Write the Nginx server block. Nginx terminates TLS, serves /static/ off disk, and proxies everything else to the socket. Create /etc/nginx/sites-available/myapp:
server {
listen 443 ssl;
server_name myapp.example.com;
ssl_certificate /etc/letsencrypt/live/myapp.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/myapp.example.com/privkey.pem;
location /static/ {
alias /srv/myapp/static/;
}
location / {
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://unix:/run/gunicorn.sock;
}
}
The X-Forwarded-Proto header lets your framework know the original request was HTTPS, which Django in particular needs for secure cookies and redirects.
7. Enable the site and reload Nginx. Link the config in, test the syntax, then reload.
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
nginx -t must report both lines before you reload:
nginx: configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
8. Deploy new code with a graceful reload. After pulling new code, tell Gunicorn to reload without dropping requests. systemctl reload runs the ExecReload you set, which sends the master a SIGHUP; the master starts fresh workers and retires the old ones only once they finish their current requests.
sudo systemctl reload gunicorn.service
There is no output on success. Confirm the master stayed up and workers cycled with journalctl -u gunicorn --since '1 min ago', which should show Handling signal: hup followed by new worker PIDs. Note that a SIGHUP does not re-read the unit file itself — if you change --workers or another ExecStart flag, run daemon-reload and restart, not reload.
Validate it works
Check the three layers in order. First, the socket exists with the right owner:
ls -l /run/gunicorn.sock
srw-rw---- 1 appuser www-data 0 Jul 20 09:14 /run/gunicorn.sock
Second, the service is healthy — systemctl is-active gunicorn prints active. Third, a request through Nginx returns your app, not an error page:
curl -sSI https://myapp.example.com/
HTTP/2 200
server: nginx
content-type: text/html; charset=utf-8
A 200 (or your app’s expected status) coming back through port 443 means all three layers are talking. If you get a 502, the request reached Nginx but not Gunicorn — go to troubleshooting.
Troubleshooting
- 502 Bad Gateway. Nginx cannot reach the socket. Confirm Gunicorn is running (
systemctl status gunicorn) and the socket exists. The usual cause is permissions: Nginx’s user must be in the socket’s group. On SELinux systems (RHEL, Fedora, Rocky), Nginx is also blocked from connecting to a socket by default — the audit log shows the denial and the fix issudo setsebool -P httpd_can_network_connect 1. Checksudo tail /var/log/nginx/error.logforconnect() to unix:/run/gunicorn.sock failed (13: Permission denied). - Worker timeout on slow requests. The log shows
[CRITICAL] WORKER TIMEOUT (pid:NN)and the request 500s. A worker exceeded--timeoutseconds without responding. If the work is legitimately slow, raise--timeout, but the better fix for genuinely long jobs is to move them to a background queue rather than hold an HTTP worker hostage. Requests that are slow because they wait on I/O are the case for thegthreadworker class. - App import path or WorkingDirectory wrong. The service flaps between
activatingandfailed, andjournalctl -u gunicornshowsModuleNotFoundErrororFailed to find attribute.WorkingDirectorymust be the directory your import path is relative to, and theapp:appargument must match your actual module and callable. Reproduce it fast by running the exactExecStartcommand by hand asappuser. - Permission denied on /run at boot. Files in
/runare wiped on reboot, so a socket you created by hand disappears. This is exactly why step 3 uses agunicorn.socketunit — systemd recreates it every boot with the owner and mode you declared. If you bypassed the socket unit and bound the socket directly inExecStart, addRuntimeDirectory=gunicornto the service so systemd manages/run/gunicornfor you. - Too many or too few workers. All workers busy under light load usually means each request is slow — check for a blocking call, not worker count. Conversely, if the box is memory-starved and swapping, you have too many workers for the RAM; each one holds a full copy of the app. Start at
(2 * CPU) + 1, then adjust based on real CPU and memory use, not a guess.
When this is the wrong approach
Gunicorn is a WSGI server, and WSGI is synchronous. If your app is built on an ASGI framework — FastAPI, Starlette, or Django running under ASGI to use async views and WebSockets — Gunicorn alone is the wrong tool. Run Uvicorn there, either directly or as a Gunicorn worker class, so the async event loop is actually used.
If you deploy in containers, most of this moves. The container is your process supervisor, so you drop the systemd units and run Gunicorn as the container’s foreground command (--bind 0.0.0.0:8000, binding a port rather than a socket because Nginx or an ingress lives in a separate container). And for a tiny internal tool with a handful of users and no uptime expectation, this whole apparatus is more than the job needs — flask run behind a reverse proxy is fine for something you alone use on a trusted network, though never for anything facing the internet.
For deeper background, the Gunicorn deployment documentation covers worker classes and tuning in detail, and if you are weighing Gunicorn against the alternative, the uWSGI with Nginx guide walks through the same job with a different server.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.