๐Ÿ  VisualStudioTutor.com  ยท  Python Tutorial Home  ยท  Python Lesson 29 of 40
Lesson 29 of 40 DevOps Advanced โฑ 35 min

Docker & Containerizing Python Apps

Write efficient Dockerfiles for Python, multi-stage builds, docker-compose for dev, health checks, and non-root user security.

Part 1: What You Will Learn

  • Package a Python application in a Docker image.
  • Write a small, cache-friendly Dockerfile.
  • Exclude unnecessary files with .dockerignore.
  • Run the container as a non-root user and add a health check / Compose configuration.

Part 2: Key Concepts

A container packages an application together with its runtime and dependencies. A Docker image is the reusable build artifact; a container is a running instance of that image. Good Dockerfiles keep images small, avoid running as root, and copy dependency files before application code so build caching works efficiently.

Part 3: Topic-Specific Code Examples

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def home() -> dict[str, str]:
    return {"message": "Python app running in Docker"}

@app.get("/health")
def health() -> dict[str, str]:
    return {"status": "ok"}
fastapi
uvicorn[standard]
FROM python:3.13-slim

WORKDIR /app

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

RUN useradd --create-home appuser
COPY --chown=appuser:appuser app.py .
USER appuser

EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health')"

CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
__pycache__/
*.pyc
.venv/
.git/
.env
*.db
services:
  web:
    build: .
    ports:
      - "8000:8000"
    environment:
      APP_ENV: development
docker build -t python-tutorial-app .
docker run --rm -p 8000:8000 python-tutorial-app
# or
docker compose up --build

Part 4: How the Example Works

The dependency file is copied before app.py, allowing Docker to reuse the dependency layer when only application code changes. The image creates an unprivileged appuser, exposes port 8000, and defines a health check that calls the APIโ€™s /health route. Compose records the run configuration in a file instead of a long command.

Part 5: Hands-On Practice

Mini project โ€” Containerize Your Student API. Take the FastAPI project from Lesson 24, add requirements.txt, a Dockerfile, and .dockerignore. Build the image, run it on port 8000, open /docs, then stop and remove the container.

Part 6: Next Steps

Run and modify the examples in Visual Studio 2026, then continue to Lesson 30. Return to Python Tutorial Home to review the complete curriculum.

๐Ÿ“˜ Want the complete guide with projects? Get the book โ†’