Docker: Package Your App
Why containers solve "it works on my machine", images and containers, a production Dockerfile for Flask with gunicorn, layer caching, .dockerignore, small and secure images, and running an app with its database using Docker Compose.
Images and containers
Your app needs the right Python version, the right packages, system libraries and settings. Docker packages all of that into an image, a read-only template built from a recipe called a Dockerfile. Running an image gives a container: an isolated process with its own files, which behaves the same on your laptop, a colleague's computer and a cloud server. Most cloud platforms can run any container, so Docker is the most portable way to deploy.
docker build -t clinic-app .builds an image from the Dockerfile in the current folder.docker run -p 8000:8000 --env-file .env clinic-appruns it, connecting port 8000 on your computer to port 8000 in the container.
Walk through a Dockerfile
Step through a production-ready Dockerfile for a Flask app, one instruction at a time.
Interactive: this part runs in your browser.
The complete Dockerfile
And a .dockerignore so secrets and junk never enter the image:
Gunicorn is a production web server for Python: it runs several worker processes so many requests are handled at once. Add it to requirements.txt. (Gunicorn does not run on Windows itself, but it runs fine inside the Linux container. Without Docker on Windows, waitress is an alternative.)
Docker Compose: the app and its database
Real apps need more than one container, for example Flask plus PostgreSQL. Docker Compose describes them in one file and starts them together with docker compose up:
The volume keeps the database's files when containers are recreated. Inside Compose, containers reach each other by service name (db). The passwords here are for local development only.
Quiz
1. Why copy requirements.txt and install packages before copying the rest of the code?
2. What is the difference between an image and a container?
3. Why list .env in .dockerignore?
4. Why run the app as a non-root user in the container?
📚 Further reading
Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.
- Docker: Get started ↗ official introduction to images, containers and Compose
- Gunicorn documentation ↗ the production server used in this course