▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Docker for Python apps
Package your app so it runs the same everywhere.
🎬 Video version coming soon — read it now
"It works on my laptop" is the oldest problem in software. Docker packages your app with its exact Python version, libraries and settings into an image that runs the same everywhere: a teammate's laptop, a test server or the cloud.
Key words
- Image: a packaged, read-only snapshot of your app and everything it needs
- Container: a running instance of an image
- Dockerfile: the recipe that builds the image
A Dockerfile for the FastAPI app
Line by line:
- FROM: start from an official slim Python image
- ENV: don't write .pyc files, and show logs immediately
- COPY requirements.txt, then RUN pip install: done before copying the code, so Docker caches the slow install step. Editing your code doesn't reinstall every library
- COPY . .: add your code
- USER appuser: don't run as root, which is a basic security practice
- CMD: the command that starts the app, listening on all interfaces inside the container
.dockerignore
Keep junk and secrets out of the image:
Build and run
-tnames (tags) the image-p 8000:8000connects port 8000 on your laptop to the container--env-file .envpasses secrets in at run time. They're never baked into the image
Open http://localhost:8000/docs and it works exactly as before, now in a container.
Useful commands
Never put secrets in the image
Anyone who gets the image can read every file in it. Pass secrets as environment variables when the container starts, or through the hosting platform's secrets settings.
In one line
A Dockerfile packages your app and its dependencies into an image that runs identically everywhere; install dependencies before copying code, run as a non-root user, and pass secrets at run time.
Share with a friend