Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 72 ยท Testing, Quality and Production

Deployment

Put a Flask app into production with gunicorn, an nginx reverse proxy, Docker, ProxyFix, environment variables and a health check endpoint.

So far you have run Flask with its development server, started by flask run. That server is convenient and nothing else. It handles requests poorly under load, it was never audited for hostile traffic, and with debug mode on, it hands out a remote Python console. To serve real visitors you need a production setup: a proper WSGI server, a reverse proxy in front of it, configuration from the environment, and a way for the platform to tell whether your app is healthy.

This lesson explains each piece and why it exists. Most of it involves real servers and cannot run in a browser tab, so those parts are shown as read-only files. The parts that are plain Python (reading configuration, health checks, the WSGI interface and the proxy headers) are runnable.

The big picture

A typical Flask deployment has four layers:

flowchart LR
    V["Visitor"] -->|"HTTPS"| N["nginx<br/>TLS, static files, buffering"]
    N -->|"HTTP on localhost"| G["gunicorn<br/>several workers"]
    G --> F["Flask app<br/>(WSGI callable)"]
    F --> D[("Database")]

The visitor never talks to Flask directly. nginx handles the public internet; gunicorn runs the Python code.

Why two servers in front of Flask?

  • gunicorn speaks the WSGI protocol to your app, runs several worker processes and restarts them if they crash.
  • nginx (or a cloud load balancer) faces the internet. It terminates HTTPS, serves static files without touching Python, and protects gunicorn from slow clients who would otherwise tie up a worker for the whole upload.

Platforms such as Heroku-style hosts, Render, Fly.io or Google Cloud Run do the nginx part for you. You provide a process that listens on a port, and they handle TLS and routing.

What a WSGI server actually does

WSGI is a very small contract: a server calls your application with a dictionary of request data (environ) and a function (start_response) to begin the reply, and the application returns the body. A Flask app object is such a callable. Gunicorn does nothing magical: it accepts a connection, builds the environ, calls your app and sends back what it returns. You can do the same by hand.

Python Calling a Flask app the way gunicorn does

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Because the contract is so small, you can swap servers (gunicorn, uWSGI, waitress, mod_wsgi) without changing your app.

Choosing and running a WSGI server

gunicorn is the usual choice on Linux and macOS. On Windows, use waitress, which is pure Python.

First, give the server something to import. A tiny wsgi.py makes the entry point explicit, especially with the application factory from The Application Factory:

Python
# wsgi.py
from myapp import create_app

app = create_app()

Then start it (read-only, because it needs a real network port):

Terminal
pip install gunicorn
gunicorn --workers 3 --bind 127.0.0.1:8000 wsgi:app

# or call the factory directly
gunicorn "myapp:create_app()"

wsgi:app means "import the module wsgi and use the object named app". Settings can also live in a Python file, which is handy for version control. Gunicorn reads gunicorn.conf.py from the working directory automatically, or you pass -c path:

Python
# gunicorn.conf.py
import multiprocessing
import os

bind = os.environ.get("BIND", "127.0.0.1:8000")
workers = int(os.environ.get("WEB_CONCURRENCY", multiprocessing.cpu_count() * 2 + 1))
timeout = 30
accesslog = "-"      # write the access log to stdout
errorlog = "-"       # write the error log to stderr

The traditional starting point for the number of workers is 2 x cores + 1. It is a guide, not a law: measure, and remember that every worker is a full copy of your app in memory. A configuration file is ordinary Python, so you can test the logic in isolation:

Python Reading a gunicorn-style config file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Setting WEB_CONCURRENCY in the environment changed the worker count without editing any file. That is exactly why environment variables are the preferred way to configure deployments.

You do not have to guess how many workers fit your server. Start with a small number, watch CPU and memory, and raise it until the machine is busy but not swapping. If your app waits on slow I/O a lot, try --threads 4 for the gthread worker type.

Configuration from the environment

The same code must run on your laptop, on a staging server and in production, with different databases and secrets. The twelve-factor approach is to keep code and configuration separate and to supply configuration through environment variables. Secrets never go into Git.

Flask makes this easy: app.config.from_prefixed_env("SHOP") reads every environment variable that starts with SHOP_ and stores it in app.config without the prefix. Values are parsed as JSON when possible, so "25" becomes the integer 25 and "true" becomes True. More about configuration patterns is in Configuration and Environments.

A health check endpoint

Load balancers, container orchestrators and uptime monitors need a cheap URL that answers "is this app alive?". Two flavors are common:

  • Liveness (/healthz): the process is running and can answer. If this fails, restart the process.
  • Readiness (/readyz): the app can do real work, for example it can reach the database. If this fails, stop sending it traffic, but do not necessarily restart it.
Python Environment config and health checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two details worth copying: the app refuses to start without its secret instead of running insecurely, and when the database is down the liveness check still succeeds while readiness returns 503. Keep health checks fast and free of side effects, and do not expose private details in them.

Behind a reverse proxy: ProxyFix

Once nginx sits in front of gunicorn, Flask sees every request as coming from 127.0.0.1 over plain HTTP to the host 127.0.0.1:8000. The real client address, the original scheme and the public host name arrive in headers set by the proxy: X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Host. By default Flask ignores them, because any client can send fake headers.

Without correction, url_for(..., _external=True) builds http:// links, request.is_secure is false, secure-cookie logic misbehaves and your logs show the proxy's address for everybody. Werkzeug's ProxyFix middleware fixes this by trusting a stated number of proxies.

Python ProxyFix and forwarded headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Without ProxyFix the headers are ignored and the app reports the test client's address and an http://localhost/ URL. With it, the address, scheme and host come from the headers. In the last call, the visitor sent a fake first hop (1.2.3.4), but with x_for=1 only the last entry, the one added by your own proxy, is trusted.

Set x_for, x_proto and x_host to the exact number of proxies in front of your app (usually 1). If you trust headers when no proxy is stripping them, visitors can pretend to be any IP address or force https links.

The matching nginx side must actually set those headers:

NGINX
server {
    listen 80;
    server_name shop.example.com;

    location /static/ {
        alias /srv/shop/static/;
        expires 30d;
    }

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Host $host;
    }
}

Serving /static/ straight from nginx keeps those requests away from Python entirely. For HTTPS, add a listen 443 ssl block with a certificate; free certificates from Let's Encrypt can be requested and renewed with certbot.

Docker

A container bundles your code, Python and dependencies into one image that runs the same everywhere. A minimal, read-only Dockerfile for a Flask app:

DOCKERFILE
FROM python:3.13-slim

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

RUN useradd --create-home appuser
USER appuser

EXPOSE 8000
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "3", "wsgi:app"]

Notes on this file:

  • Copying requirements.txt first lets Docker reuse the cached dependency layer when only your code changes.
  • PYTHONUNBUFFERED=1 makes logs appear immediately on stdout, where the platform collects them (see Logging and Debugging).
  • Running as a non-root user limits the damage if the app is compromised.
  • Secrets are passed at run time (docker run -e SHOP_SECRET_KEY=... or your platform's secret store), never baked into the image.

You build and run it with docker build -t shop . and docker run -p 8000:8000 --env-file prod.env shop. A HEALTHCHECK or your orchestrator's probe can call the /healthz route from the previous section.

Dockerizing step by step

The short Dockerfile above is a good start. Here is the full workflow for a typical app with a PostgreSQL database, step by step. Every file below was built and run with Docker Compose while writing this lesson; the app was a small factory-based project (shop/__init__.py, wsgi.py) with /, /healthz and /readyz routes, where /readyz runs SELECT 1 against the database. The commands and files are read-only here because the browser cannot run containers.

TEXT
shop/
  shop/__init__.py      # create_app()
  wsgi.py               # app = create_app()
  requirements.txt
  Dockerfile
  .dockerignore
  compose.yaml

Step 1: pin your dependencies

TEXT
# requirements.txt
flask>=3.1,<3.2
gunicorn>=23
sqlalchemy>=2.0,<2.1
psycopg[binary]>=3.2,<4

gunicorn must be in the file, because the container runs it instead of flask run. For fully repeatable builds, generate a lock file (pip-compile, uv pip compile, or pip freeze) and install from that. Remember the database driver (Flask with PostgreSQL and MySQL).

Step 2: a .dockerignore

COPY . . copies everything in the folder. Keep secrets, caches and your local virtual environment out of the image:

TEXT
.git
.venv
__pycache__/
*.pyc
.env
.pytest_cache/
tests/
compose.yaml
Dockerfile

If .env ended up in an image, anyone who can pull the image can read your secrets, so this file is a security measure, not just a size optimization.

Step 3: a multi-stage Dockerfile

Building packages can require compilers and caches that the running app does not need. A multi-stage build installs dependencies into a virtual environment in a first stage and copies only that folder into a clean second stage:

DOCKERFILE
# syntax=docker/dockerfile:1
FROM python:3.13-slim AS build
ENV PIP_DISABLE_PIP_VERSION_CHECK=1 PIP_NO_CACHE_DIR=1
WORKDIR /build
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN pip install -r requirements.txt

FROM python:3.13-slim AS runtime
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PATH="/opt/venv/bin:$PATH"
RUN useradd --create-home --uid 10001 appuser
WORKDIR /app
COPY --from=build /opt/venv /opt/venv
COPY --chown=appuser:appuser . .
USER appuser
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
  CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=2).status == 200 else 1)"
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "3", "--access-logfile", "-", "wsgi:app"]

What each part does:

  • python:3.13-slim is a small Debian-based image. Pin the version you tested. (Alpine images are smaller but use musl, which makes some binary wheels unavailable or slow.)
  • Copying requirements.txt before the code means Docker reuses the cached dependency layer when only your code changed, so rebuilds take seconds.
  • PYTHONUNBUFFERED=1 makes logs appear immediately; --access-logfile - sends gunicorn's access log to standard output, where Docker collects it (docker compose logs web).
  • A non-root user (USER appuser) limits what a compromised app can do. The check docker compose exec web id shows uid=10001(appuser).
  • HEALTHCHECK lets Docker mark the container healthy or unhealthy. It uses Python's standard library, so the image does not need curl.
  • The server binds to 0.0.0.0: inside a container, 127.0.0.1 would be unreachable from outside the container.
  • The JSON form of CMD (an array) runs gunicorn as the main process, so it receives the stop signal and shuts down gracefully.

The resulting image for this small app was about 266 MB, most of it Python itself and the PostgreSQL driver.

Step 4: Compose for the app and the database

An app rarely runs alone. A compose.yaml describes the services together:

YAML
services:
  web:
    build: .
    ports:
      - "8000:8000"
    environment:
      DATABASE_URL: postgresql+psycopg://shop:${DB_PASSWORD:-dev-password}@db:5432/shop
    depends_on:
      db:
        condition: service_healthy
    restart: unless-stopped

  db:
    image: postgres:17
    environment:
      POSTGRES_USER: shop
      POSTGRES_PASSWORD: ${DB_PASSWORD:-dev-password}
      POSTGRES_DB: shop
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U shop -d shop"]
      interval: 5s
      timeout: 3s
      retries: 10

volumes:
  pgdata:

Points to notice:

  • The app reaches the database at the host name db, the service name, not localhost.
  • depends_on with condition: service_healthy waits until PostgreSQL accepts connections, so the app does not crash at startup. (Still write the app to retry or fail clearly; databases can restart later.)
  • ${DB_PASSWORD:-dev-password} reads the password from your shell or a .env file next to compose.yaml, with a development default. In production set a strong value through the environment or your platform's secrets, and keep .env out of Git.
  • The named volume pgdata keeps the data when containers are recreated. docker compose down keeps it; docker compose down -v deletes it.
  • The database port is not published. Only web needs it, and an exposed database is a common mistake. Publish it as 127.0.0.1:5432:5432 only when you want to use a local client during development.

Step 5: run and check

TEXT
docker compose up -d --build
docker compose ps                    # web should become "healthy"
curl http://localhost:8000/          # Hello from the shop
curl http://localhost:8000/readyz    # {"status":"ready"}  (proves the web container reaches the database)
docker compose logs -f web           # access log lines from gunicorn
docker compose down                  # stop and remove containers, keep the data volume

Run one-off commands in the same image with docker compose run --rm web flask --app wsgi db upgrade or docker compose exec web sh. Run migrations as a separate command or job (Migrations), not inside every web container at startup: with several containers starting at once, they would race to change the schema.

Step 6: best practices checklist

  • One process per container: gunicorn only. Put nginx, Redis, a worker and the database in their own services.
  • Choose the worker count for the container's CPU limit (2 x cores + 1 is a starting point) and remember each worker has its own database connection pool.
  • Keep secrets out of the image and out of ENV lines in the Dockerfile; pass them at run time.
  • Tag images with a version or commit hash (shop:2026-03-01), not just latest, so you can roll back.
  • Add a /healthz route for the container check and a /readyz that tests dependencies (see the health checks section above).
  • Scan images (docker scout, Trivy) and rebuild regularly to receive base-image security updates.
  • Behind a reverse proxy, add ProxyFix (WSGI Middleware) so request.remote_addr and url_for(..., _external=True) are correct.
  • For production hosting, push the image to a registry and let your platform run it; Compose is excellent for development and small single-host deployments.

Platform-as-a-service and the Procfile

Not every project needs a server you manage. A platform-as-a-service (Heroku-style platforms, Render, Railway, Fly.io and similar) builds your repository and runs it for you. They all ask for the same four things:

  1. A requirements.txt (or pyproject.toml) with exact dependencies, including your WSGI server.
  2. A start command. Heroku-style platforms read it from a file named Procfile in the repository root.
  3. Configuration through environment variables, never committed files: SECRET_KEY, DATABASE_URL.
  4. Listening on the port the platform gives you in $PORT.
TEXT
# Procfile
web: gunicorn --workers 3 --bind 0.0.0.0:$PORT wsgi:app
TEXT
# requirements.txt
flask==3.1.*
gunicorn==23.*
psycopg[binary]==3.*
Terminal
# The usual Heroku-style flow (read-only)
git init && git add . && git commit -m "first deploy"
heroku create my-flask-demo
heroku config:set SECRET_KEY="$(python -c 'import secrets; print(secrets.token_hex(32))')"
git push heroku main
heroku logs --tail

Two traps: the platform's file system is temporary, so uploads and SQLite files disappear on every restart (use object storage and a managed database), and the platform terminates HTTPS for you, so configure ProxyFix as shown earlier. Free tiers change often; check the current pricing and rules of any platform before you rely on it.

Keeping it running

On a plain Linux server (no containers), a systemd unit keeps gunicorn running and restarts it after crashes and reboots:

INI
[Unit]
Description=Shop (gunicorn)
After=network.target

[Service]
User=shop
WorkingDirectory=/srv/shop
EnvironmentFile=/etc/shop/env
ExecStart=/srv/shop/.venv/bin/gunicorn --workers 3 --bind 127.0.0.1:8000 wsgi:app
Restart=always

[Install]
WantedBy=multi-user.target

A pre-launch checklist

  • DEBUG is off and the interactive debugger is unreachable.
  • SECRET_KEY and other secrets come from the environment and are long and random.
  • Traffic is served over HTTPS, with SESSION_COOKIE_SECURE=True and SESSION_COOKIE_HTTPONLY=True.
  • ProxyFix matches the real number of proxies.
  • Static files are served by nginx or a CDN with long cache times (Performance and Caching).
  • Logs go to stdout or a collector, and errors reach an error tracker.
  • Database migrations run as a deployment step, and backups exist and have been restored at least once.
  • /healthz and /readyz are wired into monitoring.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should you not serve a public site with flask run?

    The built-in server is for development. Use a production WSGI server such as gunicorn or waitress, usually behind a reverse proxy.
  2. 2. In gunicorn wsgi:app, what does wsgi:app mean?

    The format is module:object. Gunicorn imports the module and calls the named WSGI callable for each request.
  3. 3. Behind nginx, request.is_secure is false and generated links use http. What is the usual fix?

    Flask sees only the local connection from the proxy. ProxyFix reads the forwarded headers, but only the proxies you say you trust.
  4. 4. A database outage should make the load balancer stop sending traffic, without restarting the process. Which check does that?

    Readiness reports whether the app can do real work. Liveness only says the process is up.
  5. 5. Where should the production SECRET_KEY live?

    Secrets stay out of version control and out of images. Supply them through the environment or the platform's secret manager.

Summary

  • Production needs a WSGI server (gunicorn, or waitress on Windows) instead of the development server, usually behind nginx or a platform load balancer.
  • A WSGI app is just a callable; servers differ in how they run it, not in how your code is written.
  • Configure with environment variables (from_prefixed_env, WEB_CONCURRENCY) and fail fast when a required secret is missing.
  • Use ProxyFix with the exact proxy count so client IPs, schemes and hosts are correct, and have the proxy set the forwarded headers.
  • A Dockerfile or systemd unit keeps the process running; expose /healthz and /readyz for monitoring.
  • Dockerize in steps: pinned requirements, a .dockerignore, a multi-stage Dockerfile with a non-root user and health check, and a Compose file with a healthy database dependency, a named volume and no published database port.
  • Walk through the pre-launch checklist: debug off, HTTPS, secrets, logs, migrations, backups.

Now it is time to build complete applications in Project: A Blog.