Docker for Python: Compose, Dockerfile, image size, slim vs alpine, venv and dev setup

Is Docker or Compose Python, running scripts, a Python Dockerfile, smaller images, slim vs alpine, dependencies, slow containers, venv and dev setup.

Presenting Annapurna on stage
Presenting Annapurna on stage

Key takeaways

  • Docker Compose v2 is written in Go; Docker itself is not a Python library, though a Python SDK exists.
  • Install dependencies before copying code so Docker caches the dependency layer.
  • Use python slim images, multi-stage builds and .dockerignore to keep images small.
  • Slow containers usually come from emulation, bind mounts, Alpine builds or resource limits.
  • Use venv for quick local work and Docker for consistent environments and deployment.

Docker is not a Python tool, but it is one of the best ways to package and run Python applications: a Dockerfile describes the Python version, dependencies and code, producing an image that runs the same everywhere. I ship Python and FastAPI services with Docker, so this page covers whether Docker or Docker Compose is Python, running Python scripts, an example Dockerfile, shrinking images, choosing base images, dependencies, why containers can feel slow, Docker versus venv, and development setups.

Is Docker Compose written in Python?

Not anymore. The original docker-compose, version 1, was written in Python and installed with pip. Docker Compose version 2, used today as the docker compose command, was rewritten in Go and ships as a Docker CLI plugin.

Also asked as: is docker compose python

Compose files are YAML, not Python, and describe multiple services, networks and volumes, such as a FastAPI app, a PostgreSQL database and a Redis cache. Use docker compose up to start them together. If you see old instructions with the hyphenated docker-compose command, they refer to version 1, which is deprecated. You can still control Docker from Python with the official Docker SDK for Python, but Compose itself no longer depends on Python.

Is Docker a Python library?

No. Docker is a containerisation platform, mostly written in Go, that packages applications with their dependencies into images and runs them as isolated containers. It works with any language, not just Python.

Also asked as: example python docker file

There is, however, an official Python library called docker, the Docker SDK for Python, which lets Python code build images, start and stop containers, and read logs by talking to the Docker daemon. It is useful for automation scripts, test harnesses and tools. For most developers, Docker is used from the command line and Dockerfiles, while Python runs inside the containers. Install Docker Desktop or Docker Engine separately from any Python packages.

Can Docker run Python scripts?

Yes. Run a script with the official image without installing Python locally: docker run --rm -v "$PWD":/app -w /app python:3.12-slim python script.py. This mounts your folder into the container and runs the script.

For repeated use, build an image with your script and dependencies baked in, so it runs identically on any machine, CI runner or server. Pass configuration through environment variables and secrets, not hard-coded values. For scheduled jobs, run containers from cron, Kubernetes CronJobs or cloud schedulers. Containers stop when the script finishes, which suits batch tasks. Use --rm to clean up stopped containers, and volumes or bind mounts to persist output files. Logs from print statements appear in docker logs.

What does an example Python Dockerfile look like?

A solid starting Dockerfile uses a slim base image, installs dependencies before copying code for better caching, and runs as a non-root user. Here is a simple FastAPI example.

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN useradd -m appuser
USER appuser
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Build with docker build -t myapp . and run with docker run -p 8000:8000 myapp. Add a .dockerignore file excluding virtual environments, caches and secrets. Set PYTHONUNBUFFERED=1 so logs appear immediately, and pin dependency versions in requirements.txt for reproducible builds.

How do you reduce Python Docker image size?

Use a slim base image, install with pip --no-cache-dir, remove build tools after compiling, and use multi-stage builds that install dependencies in a builder stage and copy only the results into a clean runtime image.

Also asked as: how to reduce python docker image size

Also add a .dockerignore to exclude .git, virtual environments, tests and data files; combine RUN commands to reduce layers; avoid installing unnecessary system packages; and check heavy dependencies, since libraries like PyTorch dominate image size, so use CPU-only wheels when you do not need a GPU. Tools such as docker image history and dive show which layers are large. Smaller images pull faster, start faster and reduce the attack surface.

What is the difference between Python Docker images?

The official python image comes in variants: the full Debian-based image with many build tools, slim with a minimal Debian, and alpine based on Alpine Linux with musl. Tags such as bookworm name the Debian release.

Use slim for most applications: it is small and compatible with prebuilt Python wheels. The full image helps when you need to compile packages with many system dependencies. Alpine is tiny, but many Python wheels target glibc, so pip may compile packages from source on Alpine, making builds slow and images sometimes larger, which is why many teams avoid it for Python. Pin a specific Python version, such as 3.12-slim, rather than latest, for reproducible builds.

How do you handle Python dependencies in a Docker image?

Copy your dependency file first, install it, then copy the rest of your code. Docker caches the dependency layer, so code changes do not trigger reinstalling packages, which speeds up rebuilds dramatically.

Also asked as: how do you use python dependencies in a docker image

Pin exact versions with a lock file from pip-tools, Poetry or uv, so builds are reproducible. uv can install dependencies very quickly inside Docker. For private packages, use build secrets rather than embedding credentials in images. Avoid virtual environments inside containers unless you use multi-stage builds where copying a venv is convenient. Rebuild images regularly to pick up security patches, and scan them with tools such as Docker Scout or Trivy.

Why is the Python Docker image slower than Python on your machine?

Common causes: running an amd64 image on an Apple silicon Mac through emulation, slow bind-mounted file systems on Mac and Windows, Alpine images using musl and compiling packages, or CPU and memory limits set on the container.

Also asked as: why is the `python` docker image slower than python of my local machine

Fixes: use images matching your CPU architecture, such as arm64 on Apple silicon; keep heavy file access inside the container or use named volumes instead of bind mounts; switch from Alpine to slim; and check Docker Desktop's resource settings. Also compare Python versions, since your local interpreter may be newer and faster. On Linux servers, containerised Python normally runs at near-native speed, so differences usually point to configuration rather than Docker itself.

Docker vs Python venv: which should you use?

A venv isolates Python packages for one project on your machine; Docker isolates the whole environment, including operating system libraries, the Python version and services. Use venv for lightweight local development and Docker for consistent deployment and multi-service setups.

Many developers combine them: a venv or uv for fast local iteration, and Docker for testing in production-like conditions and deploying. Docker shines when your app needs system libraries, databases or specific Python versions, or when teammates use different operating systems. venv is simpler and faster for scripts and learning. In CI, Docker ensures tests run in the same environment as production, removing works-on-my-machine problems.

How do you use Docker for Python development?

Use Docker Compose to run your app alongside databases and caches, mount your source code as a volume for live reload, and use VS Code Dev Containers or similar tools to develop inside the container with debugging and extensions.

Also asked as: how to use docker for python development

A typical setup: a compose.yaml with an app service running uvicorn with reload, a PostgreSQL service with a named volume, and environment variables from a .env file excluded from git. VS Code's Dev Containers extension opens the project inside the container, giving everyone the same Python version and tools. Keep separate Dockerfile targets for development and production, using multi-stage builds, so production images stay small while development includes testing tools.

Sources

  1. Docker Hub, Official Python imagehub.docker.com
  2. Docker Docs, Docker Composedocs.docker.com
  3. Docker SDK for Python, documentationdocker-py.readthedocs.io
  4. Docker Docs, Multi-stage buildsdocs.docker.com
  5. Visual Studio Code, Developing inside a containercode.visualstudio.com
  6. uv, Using uv in Dockerdocs.astral.sh
Pranjul Rathour
Pranjul Rathour
GenAI Engineer · India

GenAI engineer and AI product builder with 2+ years shipping production-grade AI systems: RAG pipelines, fine-tuned LLMs, hybrid retrieval and multi-modal apps across vision, speech and OCR, architected end to end from ingestion to deployment. Leads engineering for SCULT INDIA's 14-member team, founded the 500+ member TechVerse Enclave community and has mentored 200+ students. Three hackathon first prizes: Changethon 2025 (IIT Roorkee), Product Genesis at Vividhotsava 2025 (CSJMU) and BYTEBATTLE (MeetKats).

Open to GenAI roles, hackathon judging, mentorship sessions and guest talks at colleges. For campus sessions the inviting institution covers the visit end to end: travel (a First AC train ticket for journeys up to five hours, a flight for anything longer), accommodation, meals, and pickup and drop; the honorarium and workshop fees are negotiable on WhatsApp or on the call, and requests are welcome from institutions that can cover the visit this way. Email pranjulrathour41@gmail.com.

Keep reading

More on Shipping AI apps

All Shipping AI apps guides →
Campus talks · hackathon judging · mentoring

Want this as a live session at your college?

Open to GenAI roles, hackathon judging, mentorship sessions and guest talks at colleges. For campus sessions the inviting institution covers the visit end to end: travel (a First AC train ticket for journeys up to five hours, a flight for anything longer), accommodation, meals, and pickup and drop; the honorarium and workshop fees are negotiable on WhatsApp or on the call, and requests are welcome from institutions that can cover the visit this way.

Pranjul Rathour, GenAI engineer in India