Skip to content
Tutorials Center
My learning

Topics

Lesson 126 of 149 ยท Data and the Web

Deploying Python Web Apps

Learn how to take a Python web app live. Understand WSGI and ASGI, run Gunicorn or Uvicorn behind a proxy, read settings from the environment, package with Docker and pick a host.

Your Flask, Django or FastAPI app works on your laptop with the built-in development server. Deployment means running it on a computer that is always on, reachable from the internet, and able to survive crashes, restarts and traffic. The good news: the recipe is almost the same for every Python web framework.

This lesson explains the pieces in the order a request meets them: the web server, the application server (WSGI or ASGI), your app and its configuration. Then you package it in a container and look at the common places to host it. You can run the Python parts (the WSGI and ASGI contracts and the settings loader) right here.

The deployment picture

A request travels through layers

Browser Sends an HTTPS request
Reverse proxy nginx, Caddy or a cloud load balancer
App server Gunicorn or Uvicorn, many workers
Your app Flask, Django or FastAPI

Each layer has one job.

1 / 2

Why not just run python app.py or flask run? The development server handles one kind of traffic poorly, restarts for code changes, shows debug pages that leak source code, and has no process management. In production you use an application server designed for that, in front of which sits a reverse proxy that terminates HTTPS and serves files efficiently.

WSGI and ASGI: the contract

Python web servers and frameworks agree on a small interface so you can mix them freely.

  • WSGI (the classic, synchronous standard): the server calls app(environ, start_response) once per request. Flask and Django (in its classic mode) are WSGI apps. Servers: Gunicorn, uWSGI, Waitress (works on Windows).
  • ASGI (the asynchronous successor): the server awaits app(scope, receive, send). It supports async, WebSockets and long-lived connections. FastAPI, Starlette and modern Django are ASGI apps. Servers: Uvicorn, Hypercorn, Daphne.

Here is a complete WSGI application, called by hand the way Gunicorn would call it for every request.

Python A WSGI app without a server

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.

That is all a WSGI server does: parse HTTP into environ, call your function, send the status, headers and body back. Gunicorn adds the hard parts around it, such as a pool of worker processes, timeouts and graceful restarts.

The ASGI version is a coroutine that receives messages and sends messages:

Python An ASGI app, driven by hand

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.

You rarely write these by hand. A framework object is the callable: when you run gunicorn myapp:app or uvicorn myapp:app, the part after the colon is the name of that callable inside the module.

Running an app server

Install the server in your virtual environment and point it at your app. The examples assume a file main.py with a variable app.

Terminal
# WSGI app (Flask, classic Django): Gunicorn
pip install gunicorn
gunicorn --workers 3 --bind 127.0.0.1:8000 main:app

# ASGI app (FastAPI, Starlette): Uvicorn, either on its own...
pip install uvicorn
uvicorn main:app --host 127.0.0.1 --port 8000 --workers 3

# ...or as Gunicorn workers, for Gunicorn's process management
gunicorn -k uvicorn.workers.UvicornWorker --workers 3 --bind 127.0.0.1:8000 main:app

How many workers? A worker is a separate process, so Python's GIL does not limit you. A common starting point for synchronous apps is 2 x CPU cores + 1. For async apps, start near the number of cores, because each worker already handles many connections. Measure, then adjust, because memory per worker also matters. For Django, run python manage.py collectstatic once during deployment, and do not use manage.py runserver or fastapi dev in production.

Bind to 127.0.0.1 when a reverse proxy runs on the same machine. Binding to 0.0.0.0 exposes the app server directly, which is only right inside a container or private network.

Keep the server alive with a process manager: systemd on a Linux server, or the container platform's restart policy. A minimal systemd unit looks like this:

INI
[Unit]
Description=My Python app
After=network.target

[Service]
User=app
WorkingDirectory=/srv/myapp
EnvironmentFile=/etc/myapp.env
ExecStart=/srv/myapp/.venv/bin/gunicorn --workers 3 --bind 127.0.0.1:8000 main:app
Restart=on-failure

[Install]
WantedBy=multi-user.target

The reverse proxy and HTTPS

A web server such as nginx or Caddy sits in front. It speaks HTTPS to the world (certificates from Let's Encrypt are free and Caddy gets them automatically), serves static files itself, buffers slow clients and forwards the rest to your app server.

NGINX
server {
    listen 80;
    server_name example.com;

    location /static/ { alias /srv/myapp/static/; }

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

Because the app only sees the proxy, tell your framework to trust the X-Forwarded-* headers (Uvicorn: --proxy-headers --forwarded-allow-ips=127.0.0.1; Flask: werkzeug.middleware.proxy_fix.ProxyFix; Django: SECURE_PROXY_SSL_HEADER). Otherwise generated links use http:// and client IPs are all 127.0.0.1.

Configuration from the environment

The same code runs on your laptop, a test server and production, with different settings: database URL, secret keys, debug mode, allowed hosts. The rule from the "twelve-factor app" method is simple: keep configuration in environment variables, never in the code or the repository. Secrets committed to Git stay in its history forever.

Read variables once at startup, convert and validate them, and fail fast when something is missing.

Python A settings loader that fails fast

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.

For bigger apps the pydantic-settings package does the same job with less code, reading real environment variables and a local .env file (which you add to .gitignore). Never print secrets in logs, and give each environment its own database and keys.

Two more settings deserve a rule of their own: debug mode off in production (debug pages reveal code and sometimes secrets) and a list of allowed hosts so your app only answers for your own domain names.

A health check endpoint

Platforms and load balancers need to know whether your app is alive. Add a cheap endpoint such as /health that returns 200 without touching external services, and optionally a /ready that checks the database. With FastAPI:

Python Health endpoint with FastAPI

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.

Packaging with Docker

A container bundles your code, Python and its libraries into one image that runs the same everywhere. A good Python Dockerfile is small, installs dependencies before copying code (so rebuilds are fast), and does not run as root. See Dockerfile basics and multi-stage builds in the Docker tutorial.

DOCKERFILE
FROM python:3.13-slim

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

WORKDIR /app

# 1. Install dependencies first: this layer is cached until requirements change
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 2. Copy the code
COPY . .

# 3. Do not run as root
RUN useradd --create-home app
USER app

EXPOSE 8000
HEALTHCHECK CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health')"
CMD ["gunicorn", "--workers", "3", "--bind", "0.0.0.0:8000", "main:app"]

Add a .dockerignore listing .venv, .git, __pycache__ and .env so you never copy secrets or huge folders into the image. Pass configuration at run time:

Terminal
docker build -t myapp .
docker run -p 8000:8000 --env-file production.env myapp

PYTHONUNBUFFERED=1 makes logs appear immediately; log to standard output and let the platform collect them (see logging). Pin your dependencies in requirements.txt with exact versions (or use a lock file) so a build next month installs the same libraries as today.

Where to host it

Option You manage Good for
PaaS (Render, Railway, Fly.io, Heroku-style) Just code and settings Fast start, small to medium apps
Container services (AWS ECS/Fargate, Google Cloud Run, Azure Container Apps) Image and settings Scaling and pay-per-use
Virtual server (VPS) (Hetzner, DigitalOcean, AWS EC2) Everything: OS, nginx, systemd, updates Full control, lowest cost at scale
Serverless functions (AWS Lambda) Function code Spiky or tiny workloads

On a PaaS you usually push your Git repository, tell it the start command (gunicorn main:app) and set environment variables in a dashboard. The platform builds, starts, routes HTTPS traffic and restarts crashes for you. Databases are better as managed services than as containers you babysit.

Release checklist

  • DEBUG is off, the secret key is long and random, allowed hosts are set.
  • The database is separate from the app, has backups, and you can restore one.
  • Run database migrations as an explicit step during deploy, not by accident at import time.
  • Static files are collected and served by the proxy or a CDN.
  • HTTPS works, HTTP redirects to it, and proxy headers are trusted.
  • Logs go to stdout and errors reach a tracker (Sentry or similar); a /health endpoint exists.
  • The deploy can be rolled back: keep the previous image or release available.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between WSGI and ASGI?

    Both define how a server calls your app. WSGI handles one request per call synchronously. ASGI uses async functions with receive and send, which allows long-lived connections.
  2. 2. In gunicorn main:app, what does app refer to?

    The format is module:variable. Gunicorn imports main and uses the object app as the application.
  3. 3. Why keep secrets such as the database URL in environment variables?

    Config in the environment separates code from settings. Environment variables are not encrypted by themselves, but they keep secrets out of the repository.
  4. 4. Why does the Dockerfile copy requirements.txt and run pip install before copying the rest of the code?

    Layers are cached while their inputs are unchanged. Code changes often, dependencies rarely, so installing dependencies first reuses the slow layer.
  5. 5. Why put nginx or Caddy in front of Gunicorn?

    A reverse proxy is built for the network edge: TLS, static files, buffering and load balancing. The app server focuses on running Python code.

Summary

  • Production uses an app server (Gunicorn for WSGI, Uvicorn for ASGI) behind a reverse proxy such as nginx or Caddy; never the development server.
  • WSGI is app(environ, start_response); ASGI is await app(scope, receive, send); module:variable names the app for the server.
  • Run several worker processes, keep them alive with systemd or the container platform, and trust X-Forwarded-* headers only from your proxy.
  • Configure through environment variables, validate at startup, keep debug off and secrets out of Git.
  • Docker images install dependencies first, run as a non-root user, log to stdout and get settings at run time.
  • Pick a host by how much you want to manage: PaaS, container service, VPS or serverless; add a health endpoint, backups, migrations as a deploy step and a rollback plan.

Next: Project: Rock, Paper, Scissors.