Log inSign up

Packaging a Python web application as a Docker container

Write a two stage Dockerfile based on python:3.12-slim that installs dependencies into a virtual environment, copies only that environment and your code into the final image, and runs Gunicorn as a non-root user. Build with docker build -t myapp:1.0 ., run it with Docker Compose next to its database, publish the port on 127.0.0.1 only and put Nginx or Caddy in front for HTTPS.

Topic: Python · Tested on: Ubuntu 24.04 and 22.04, Debian 12 and 13, Rocky Linux 9, AlmaLinux 9 · Updated 2026-12-03

Why put a Python app in a container?

A container fixes the interpreter version, system libraries and Python packages in one image, so what you tested is exactly what runs on the server. You can upgrade the host without touching the app, roll back by starting the previous image tag, and run several projects with different Python versions side by side. The cost is one more layer to learn. If you only run a single app and like systemd, the plain approach in Flask with Gunicorn or FastAPI is perfectly fine.

How do you install Docker on the server?

Install Docker Engine and the Compose plugin from Docker's own repository, or deploy the Docker app image, which arrives with both ready. Our Docker Engine tutorial has the repository steps for Ubuntu, Debian, Rocky and Alma. Afterwards check:

docker --version
docker compose version
sudo docker run --rm hello-world
sudo usermod -aG docker deploy   # log out and in again afterwards

Membership in the docker group is equivalent to root access, so add only trusted users.

What does the example application look like?

Any WSGI or ASGI app works. For this guide a tiny Flask app with a health endpoint is enough. Project layout:

myapp/
  app.py
  requirements.txt
  Dockerfile
  .dockerignore
  compose.yaml
# app.py
import os
from flask import Flask

app = Flask(__name__)

@app.get("/")
def index():
    return {"message": "hello from the container"}

@app.get("/health")
def health():
    return {"status": "ok"}
# requirements.txt
flask==3.1.*
gunicorn==23.*
psycopg[binary]==3.2.*

For Django replace app:app later with mysite.wsgi:application; for FastAPI use Gunicorn with -k uvicorn.workers.UvicornWorker or run uvicorn directly.

How do you write a lean, safe Dockerfile?

Use one stage to install packages and a second, clean stage to run them. Build tools stay out of the final image, and the app runs as an unprivileged user.

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

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

Copying requirements.txt before the rest of the code lets Docker reuse the dependency layer when only your source changes. If a package needs compiling, add RUN apt-get update && apt-get install -y --no-install-recommends build-essential libpq-dev in the build stage only. PYTHONUNBUFFERED makes log lines appear immediately in docker logs.

Add a .dockerignore so secrets and clutter never enter the image:

.git
.venv
__pycache__
*.pyc
.env
node_modules

How do you build and test the image?

Build with an explicit version tag, run it once by hand, and call the health endpoint.

cd ~/myapp
docker build -t myapp:1.0 .
docker image ls myapp
docker run --rm -d --name myapp-test -p 127.0.0.1:8000:8000 myapp:1.0
curl -s http://127.0.0.1:8000/health
docker inspect --format "{{.State.Health.Status}}" myapp-test
docker stop myapp-test

The image should be in the low hundreds of megabytes; if it is much larger, check what the .dockerignore missed with docker history myapp:1.0. Health status turns from starting to healthy after the first successful probe.

How do you run the app and database with Compose?

A Compose file describes the app, its database and the volume that holds the data, so one command brings everything up.

# compose.yaml
services:
  web:
    build: .
    image: myapp:1.0
    env_file: .env
    ports:
      - "127.0.0.1:8000:8000"
    depends_on:
      db:
        condition: service_healthy
    restart: unless-stopped

  db:
    image: postgres:16
    env_file: .env
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER}"]
      interval: 10s
      retries: 5
    restart: unless-stopped

volumes:
  pgdata:
# .env  (chmod 600, never committed)
POSTGRES_USER=myapp
POSTGRES_PASSWORD=use-a-long-random-password
POSTGRES_DB=myapp
DATABASE_URL=postgresql://myapp:use-a-long-random-password@db:5432/myapp
docker compose up -d --build
docker compose ps
docker compose logs -f web

Inside the Compose network the app reaches PostgreSQL by the service name db; the database port is not published at all. Migrations run with docker compose exec web python manage.py migrate for Django or your own command for other frameworks.

Why publish the port on 127.0.0.1 only?

Docker writes its own packet filter rules, and a port published as 8000:8000 is reachable from the internet even when ufw or firewalld would block it. Binding to 127.0.0.1:8000 keeps the container private, and a reverse proxy on the host terminates TLS and forwards to it. With Caddy that is two lines:

app.example.net {
    reverse_proxy 127.0.0.1:8000
}

Then allow only the web ports and SSH in the host firewall:

sudo ufw allow 80/tcp && sudo ufw allow 443/tcp          # Ubuntu, Debian
sudo firewall-cmd --permanent --add-service=http --add-service=https && sudo firewall-cmd --reload   # Rocky, Alma

The Caddy HTTPS tutorial covers the proxy, and Nginx as a reverse proxy is the alternative.

How do you deploy updates and roll back?

Bump the tag, rebuild, and let Compose replace the container. Keeping the old tag on disk makes rollback a one line change.

git pull
sed -i "s/myapp:1.0/myapp:1.1/" compose.yaml
docker compose up -d --build web
docker compose ps
# roll back: set the tag to 1.0 again, then
docker compose up -d web

Clean out old layers now and then with docker image prune, and back up the database volume with docker compose exec db pg_dump -U myapp myapp > backup.sql. The Docker Compose guide and Docker volumes guide go further.

What breaks most often in Python containers?

  • Container exits at once: read docker compose logs web; usually an import error or a missing variable.
  • App cannot reach the database: it uses localhost instead of the service name db.
  • Permission denied writing files: the app runs as uid 10001; mount a volume and set its owner, or write to /tmp.
  • Changes not visible: you restarted without --build, so the old image still runs.
  • Disk filling up: check docker system df and prune unused images and build cache.

Plans that fit this guide

Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.

All prices
PlanFits becauseSizeMonthlyOrder from
A1-2one small app with its database1 vCPU, 2 GB RAM, 50 GB NVMe$7.20/mo$43.20 for 6 months
A2-4app, database and room for builds2 vCPU, 4 GB RAM, 100 GB NVMe$14.40/mo$43.20 for 3 months
A4-8several containerised projects4 vCPU, 8 GB RAM, 180 GB NVMe$28.80/mo$86.40 for 3 months

Questions about Containerise a Python web app

Should I use the Alpine Python image?

Usually not. Many Python wheels target glibc, so on Alpine they compile from source, which makes builds slow and images bigger. The Debian based slim tag is the easier default.

Which Python tag should I pin?

Pin at least the minor version, such as python:3.12-slim or python:3.13-slim, so a rebuild never jumps to a new interpreter by surprise. Rebuild regularly to pick up security patches.

Can I use uv instead of pip in the Dockerfile?

Yes. Copy the uv binary from its official image into the build stage and run uv pip install or uv sync; it is faster, and the final stage stays the same.

Where do I keep secrets?

In an .env file with mode 600 on the server, referenced by env_file. Never bake secrets into the image, since anyone with the image can read every layer.

Does the Docker app image save setup time?

Yes. Choosing the Docker image at deploy gives you Ubuntu 24.04 with Docker Engine and Compose installed, so you can start from the build step.