Sub topic 9
Running a Python app with Gunicorn
This chapter assumes you have read the earlier chapters on WSGI and ASGI and on the request flow. It also assumes you can create a Python virtual environment and run commands in a shell on a Debian/Ubuntu-style server. Here you run a WSGI application under Gunicorn, learn how its processes are organized, and tune the settings that matter in production. Nginx and systemd come in the next chapters.
What Gunicorn does
Gunicorn ("Green Unicorn") is a WSGI HTTP server for Unix. It listens on a socket, parses HTTP requests, calls your application's WSGI callable, and writes the response back. It does not serve static files efficiently, handle TLS well, or defend against slow clients. Those jobs belong to the web server placed in front of it.
Gunicorn uses a pre-fork model. One master process starts several worker processes. Each worker loads your application and handles requests. The master never touches a request. It only starts, monitors, and replaces workers.
Install and write a minimal application
Install Gunicorn into the same virtual environment as your application. Gunicorn imports your code, so it must be able to see the same packages.
python3 -m venv /srv/myapp/venv
/srv/myapp/venv/bin/pip install gunicornA WSGI application is a callable that takes the request environment and a start_response function. Save this as /srv/myapp/app.py:
def application(environ, start_response):
body = b"Hello from WSGI\n"
start_response("200 OK", [
("Content-Type", "text/plain"),
("Content-Length", str(len(body))),
])
return [body]Start it and test it directly
Run Gunicorn from the directory that contains app.py, and test it with curl before any web server is involved. If it fails here, Nginx is not the problem.
gunicorn --workers 3 --bind 127.0.0.1:8000 app:application
curl -i http://127.0.0.1:8000/The argument app:application has the form module:callable. Gunicorn runs import app and looks up the name application. For a framework, the callable is the framework's app object. For example, Flask uses app:app and Django uses myproject.wsgi:application.
The first test should return HTTP/1.1 200 OK with the text Hello from WSGI. The response also carries a Server: gunicorn header, which shows that Gunicorn answered.
Binding: loopback, all interfaces, or a socket
The --bind option decides who can reach Gunicorn.
| Value | Meaning | When to use |
|---|---|---|
| `127.0.0.1:8000` | TCP, loopback only | Nginx on the same host, simple debugging |
| `0.0.0.0:8000` | TCP, every interface | Containers, or a separate proxy host (needs a firewall) |
| `unix:/run/gunicorn/app.sock` | Unix domain socket | Nginx on the same host, access controlled by file permissions |
With a Unix socket, the socket file's owner, group, and mode decide who can connect. Gunicorn creates it using the user it runs as, and the --umask option controls its permissions. Nginx's worker user must be able to write to the socket, usually through a shared group. The chapter on permissions covers this in detail.
Worker types and what they mean for your app
The default worker class is sync. Each worker handles one request at a time. This is simple and predictable, but a worker waiting on a slow database or an external API cannot serve anyone else. Slow clients are also a problem, which is one more reason to keep Nginx in front.
You can change the worker class with --worker-class (or -k):
| Worker class | Concurrency | Notes |
|---|---|---|
| `sync` | One request per worker | Default. Good for fast, CPU-bound handlers. |
| `gthread` | Threads inside each worker | Enabled by setting `--threads` above 1. Your code must be thread-safe. |
| `gevent` or `eventlet` | Cooperative greenlets | Needs the matching package and monkey-patch-friendly code. |
| `uvicorn.workers.UvicornWorker` | Async event loop | Runs ASGI apps. Needs the `uvicorn` package. Newer Uvicorn releases move this class to the separate `uvicorn-worker` package. |
A common starting point for a typical WSGI app is gthread with a few workers and a few threads each. If your framework is ASGI (FastAPI, Starlette, Django with ASGI), use an ASGI-capable worker class instead, because a plain sync worker cannot run an ASGI callable.
Put the settings in a config file
Long command lines are hard to review and easy to mistype. Gunicorn reads settings from a Python file, which means you can also compute values in it. Save this as /srv/myapp/gunicorn.conf.py:
import multiprocessing
bind = "unix:/run/gunicorn/app.sock"
workers = multiprocessing.cpu_count() * 2 + 1
threads = 2
timeout = 30
graceful_timeout = 30
max_requests = 1000
max_requests_jitter = 100
accesslog = "-"
errorlog = "-"
loglevel = "info"Start it with gunicorn -c gunicorn.conf.py app:application. Command-line options override values in the file.
The settings do the following:
workers = cpu_count() * 2 + 1is the starting point from the Gunicorn documentation. Treat it as a first guess. Memory use per worker often limits the count before CPU does.timeoutis how long the master lets a worker stay silent before killing and replacing it. The default is 30 seconds. Raising it hides slow code. It does not fix it.max_requestsrestarts a worker after that many requests, which limits damage from slow memory leaks. The jitter spreads the restarts so all workers do not recycle at once.- Setting
accessloganderrorlogto"-"writes to standard output and standard error. Under systemd these end up in the journal.
Controlling a running Gunicorn with signals
You manage the master process by sending it signals. Find its PID with pgrep -f "gunicorn.*app:application" | head -n 1, or by reading a file set with --pid.
| Signal | Effect |
|---|---|
| `HUP` | Reloads the configuration and starts new workers. Old workers finish their current requests and exit. |
| `TERM` | Graceful shutdown. Workers get `graceful_timeout` seconds to finish. |
| `INT` | Quick shutdown. |
| `TTIN` / `TTOU` | Add or remove one worker. |
| `USR2` | Starts a new master alongside the old one, for zero-downtime upgrades of Gunicorn itself. |
A HUP is the usual way to deploy new code when preload_app is off, because the new workers import the updated modules. Under systemd, you normally wrap this in ExecReload=/bin/kill -HUP $MAINPID.
Common errors
ModuleNotFoundError: No module named 'app'means Gunicorn was started from the wrong directory, or the module name is wrong. Use--chdir /srv/myappor setWorkingDirectoryin systemd.Connection in use: ('127.0.0.1', 8000)means another process holds the port, often a previous Gunicorn. Runss -ltnp | grep 8000to find it.WORKER TIMEOUTfollowed byWorker was sent SIGKILLmeans a request ran longer thantimeout. This shows up as a 502 at Nginx. Check for slow queries or external calls.Worker failed to bootmeans your application raised an exception during import. The traceback appears just above the message in the error log.TypeError: application() takes 0 positional arguments, or similar, means the name you passed is not a WSGI callable, or you passed an ASGI app to asyncworker.
Exercise
You run gunicorn --workers 2 --bind 127.0.0.1:8000 app:application and the log shows WORKER TIMEOUT (pid:1234), after which Nginx returns 502 for one slow endpoint. Name two different fixes and explain the trade-off of simply raising timeout.
Show answer
One fix is to make the slow handler faster, for example by adding an index to the slow query or moving the work to a background job. Another is to use gthread workers with --threads so a waiting request does not block the whole worker. Raising timeout makes the error disappear but leaves workers tied up for longer, so a few slow requests can occupy every worker and block all other traffic.