The idea
"It works on my machine" happens because machines differ: Python versions, system libraries, environment variables. A Docker image bundles your code, its runtime and dependencies into one file system snapshot. A container is a running instance of that image, isolated from the host.
A Dockerfile lists the build steps: start from a base image, install dependencies, copy code, set the start command. Order steps so rarely-changing layers (dependencies) come before often-changing ones (code), and builds stay fast thanks to layer caching.
Keep images small and safe: slim base images, no secrets baked in, a non-root user, and a .dockerignore to exclude .env, .git and data folders.
Nearly every deployment target (Cloud Run, ECS, Kubernetes, Fly, Railway) runs containers. It is the standard unit of shipping.
Words to know
- ImageA packaged, immutable snapshot of an app and its environment.
- ContainerA running instance of an image.
- LayerOne cached step of an image build.
Try it without code
Run someone else’s container
- Install Docker Desktop.
- Run: docker run -p 8080:80 nginx
- Open localhost:8080. You just ran a web server without installing it.
Use it in code
A production-ready Dockerfile for a FastAPI RAG service.
FROM python:3.12-slim AS base
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app/ app/
COPY prompts/ prompts/
RUN useradd --create-home appuser
USER appuser
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]Containerise your RAG API, get the image under 500 MB, and run it with secrets passed via --env-file.
Common mistakes
- COPY . . before installing dependencies (slow rebuilds).
- Baking .env into the image.
- Running as root.