2 min read

Using Docker for Python Development

While venv isolates Python packages, Docker isolates the entire operating system environment. This ensures that your application runs exactly the same way on your machine, your colleague's machine, and the production server.

Why use Docker instead of venv?

  • System Dependencies: If your Python package relies on a specific version of a system library (like libpq-dev for Postgres or ffmpeg), venv cannot help you. Docker can.
  • Reproducibility: "It works on my machine" becomes a thing of the past.
  • Cleanliness: You don't clutter your host OS with various tools and libraries.

Step 1: Create a Dockerfile

Create a file named Dockerfile (no extension) in your project root.

# Use an official Python runtime as a parent image
FROM python:3.11-slim

# Set the working directory in the container
WORKDIR /app

# Copy the requirements file into the container at /app
COPY requirements.txt .

# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# Copy the rest of the application code
COPY . .

# Command to run the application
CMD ["python", "main.py"]

Step 2: Build the Image

Run this command in your terminal (where the Dockerfile is located).

docker build -t my-python-app .
  • -t my-python-app: Tags the image with a name.
  • .: Specifies the current directory as the build context.

Step 3: Run the Container

docker run -it --rm --name my-running-app my-python-app
  • -it: Interactive mode (useful for seeing output).
  • --rm: Automatically remove the container when it stops.
  • --name: Assign a name to the running container.

Step 4: Development Workflow (Volumes)

Rebuilding the image every time you change a line of code is slow. Use Volumes to map your local code to the container.

# PowerShell
docker run -it --rm -v ${PWD}:/app my-python-app

# Command Prompt (cmd)
docker run -it --rm -v %cd%:/app my-python-app
  • -v ...:/app: Maps your current directory (host) to /app (container). Any change you make locally is instantly visible inside the container.

See also: Virtual Environments and Pip

programming/python/python