Run Python Projects with Docker Compose and Volume Mounting
Learn how to use Docker Compose to run your Python project with a mounted local directory, allowing seamless development and testing inside a container.
If you're developing a Python project and want an isolated, reproducible environment without polluting your host system, Docker Compose is your friend. In this guide, you'll learn how to set up a Python development environment using Docker Compose that:
- Uses the official Python Docker image.
- Mounts your local project directory inside the container.
- Opens an interactive shell for testing, scripting, or REPL work.
π³ Docker Compose Setup for Python
Hereβs a minimal docker-compose.yml
that gets you up and running:
version: "3.8"
services:
python-app:
image: python:3.11-slim
container_name: python_dev_container
working_dir: /app
volumes:
- ./:/app
command: bash
stdin_open: true
tty: true
π Explanation
- image: Uses Python 3.11 slim version to reduce container size.
- working_dir: Sets
/app
as the working directory inside the container. - volumes: Mounts your current project directory into the container.
- command: Starts a Bash shell so you can run Python commands or scripts interactively.
- stdin_open and tty: Keep the container shell open for user interaction.
π How to Run
In the terminal, from your project directory:
docker-compose run --rm python-app
This launches a container where you can run:
pip install -r requirements.txt
python main.py
β Optional: Auto-install Dependencies
You can modify the command
to install Python packages on startup:
command: >
bash -c "pip install -r requirements.txt && bash"
This ensures your dependencies are always installed when you spin up the container.
π Best Practices
Create a .dockerignore
file to exclude unnecessary files from the build context:
__pycache__/
*.pyc
.venv
.git
.env
This keeps your containers lean and builds faster.
π§ͺ Use Cases
- Testing Python scripts in an isolated environment
- Running tools with dependencies that conflict with your host
- CI/CD pipelines using Docker-based testing
- Training environments or workshops
π Conclusion
Using Docker Compose to run Python with volume mounting is a powerful way to develop in isolated environments while keeping everything in sync with your local filesystem. It's great for reproducibility, testing, and quick onboarding.
If you're running Flask, FastAPI, Jupyter, or need multi-service orchestration, this setup is just the starting point β let me know and Iβll help you scale it!
Need a Dockerfile for production or containerized APIs? Check out our related tutorials or ask below!