Python language-specific guide
This guide explains how to containerize Python applications using Docker.
Acknowledgment
This guide is a community contribution. Docker would like to thank Esteban Maya and Igor Aleksandrov for their contribution to this guide.
The Python language-specific guide teaches you how to containerize a Python application using Docker. In this guide, you’ll learn how to:
- Containerize and run a Python application
- Set up a local environment to develop a Python application using containers
- Lint, format, typing and best practices
Start by containerizing an existing Python application.
Containerize a Python application
Prerequisites
- You have installed the latest version of Docker Desktop.
Overview
Containerizing your application means packaging it together with its dependencies, configuration, and runtime into a single portable unit called a container image. Running that image creates a container, an isolated process that behaves the same on any machine, whether it's your laptop, a CI runner, or a production server.
In this section, you'll containerize a simple
FastAPI web application. You'll write a
Dockerfile that describes how to build the image, add a compose.yaml file
that defines how Docker runs your container, and then build and start the
application with one command.
You'll use Docker Hardened Images as the base. These are minimal, secure Python images maintained by Docker.
Create the application
The sample application is a minimal FastAPI service with a single endpoint
that returns a JSON greeting. Create the following files in a new
python-docker-example directory. To create all the files at once, switch to
the Scaffold script tab in the file browser and copy the shell command.
If you already have Python installed and want to verify the app works before containerizing it, you can run it locally:
$ python3 -m venv .venv
$ source .venv/bin/activate
$ pip install -r requirements.txt
$ uvicorn app:app --reload
NoteOn Windows, activate the virtual environment with
.venv\Scripts\activateinstead ofsource .venv/bin/activate.
If you don't have Python installed, skip ahead to the next section. The remaining steps run the application in a container, with no local Python required.
Create the Docker assets
Sign in to the DHI registry so Docker can pull the Python base images during the build. The available Python images are listed in the catalog.
$ docker login dhi.io
Add the following three files to your python-docker-example directory. The
Dockerfile describes how to build the image, compose.yaml defines how
Docker runs the container, and .dockerignore keeps unwanted files out of the
build context.
TipGordon, Docker's AI assistant, can generate Docker assets for your project. Ask Gordon to create a Dockerfile, Compose file, and
.dockerignoretailored to your application.