0
0
DockerHow-ToBeginner · 3 min read

How to Create a Dockerfile for Python Projects

To create a Dockerfile for Python, start with a Python base image using FROM python:3.11-slim, copy your project files, install dependencies with pip install, and define the command to run your app with CMD. This sets up a container that runs your Python code in a consistent environment.
📐

Syntax

A basic Python Dockerfile includes these parts:

  • FROM: Specifies the base Python image.
  • WORKDIR: Sets the working directory inside the container.
  • COPY: Copies your project files into the container.
  • RUN: Runs commands like installing dependencies.
  • CMD: Defines the command to start your Python app.
dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "app.py"]
💻

Example

This example Dockerfile creates a container for a Python app named app.py with dependencies listed in requirements.txt. It installs the dependencies and runs the app.

dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "app.py"]
Output
Successfully built image Container runs and executes app.py
⚠️

Common Pitfalls

Common mistakes when creating a Python Dockerfile include:

  • Not specifying a Python version in FROM, which can cause unexpected behavior.
  • Forgetting to copy requirements.txt before running pip install, leading to failed installs.
  • Not using WORKDIR, which can cause file path errors.
  • Using CMD incorrectly, such as a shell string instead of JSON array, which can cause signal handling issues.
dockerfile
Wrong:
FROM python
RUN pip install -r requirements.txt
COPY . .
CMD python app.py

Right:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "app.py"]
📊

Quick Reference

Tips for writing Python Dockerfiles:

  • Always specify a Python version tag like python:3.11-slim.
  • Use WORKDIR to set a clear working directory.
  • Copy requirements.txt first to leverage Docker cache.
  • Use pip install --no-cache-dir to keep images small.
  • Use JSON array syntax for CMD to avoid shell issues.

Key Takeaways

Start your Dockerfile with a specific Python base image like python:3.11-slim.
Copy requirements.txt and install dependencies before copying the full app to optimize build caching.
Set a working directory inside the container with WORKDIR to avoid path errors.
Use the JSON array format for CMD to run your Python app cleanly.
Avoid installing unnecessary packages to keep your image small and efficient.