DEV Community

Brad
Brad

Posted on

Docker for Python Developers: Ship Your App in 15 Minutes

Docker for Python Developers: Ship Your App in 15 Minutes

Docker eliminates the 'works on my machine' problem. Here's everything you need to containerize a Python app.

Basic 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"]
Enter fullscreen mode Exit fullscreen mode

Docker Compose

version: '3.8'
services:
  web:
    build: .
    ports:
      - "5000:5000"
    environment:
      - DATABASE_URL=postgresql://user:pass@db/mydb
    depends_on:
      - db
  db:
    image: postgres:15
    environment:
      POSTGRES_PASSWORD: pass
      POSTGRES_DB: mydb
Enter fullscreen mode Exit fullscreen mode

Multi-stage Build (smaller image)

# Stage 1: Build
FROM python:3.11 AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --user -r requirements.txt

# Stage 2: Runtime (300MB smaller!)
FROM python:3.11-slim
WORKDIR /app
COPY --from=builder /root/.local /root/.local
COPY . .
ENV PATH=/root/.local/bin:$PATH
CMD ["python", "app.py"]
Enter fullscreen mode Exit fullscreen mode

Common Commands

docker build -t myapp:latest .        # Build
docker run -d -p 5000:5000 myapp      # Run
docker logs -f myapp                  # Follow logs
docker exec -it myapp bash            # Shell inside container
docker-compose up -d                  # Start all services
docker-compose down                   # Stop all
Enter fullscreen mode Exit fullscreen mode

Python Health Check

from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/health')
def health():
    return jsonify({'status': 'ok'})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
Enter fullscreen mode Exit fullscreen mode

Docker + Python is the modern standard for production deployments. Learn it once, use it everywhere.


Save hours of manual work! I built a complete Python Business Automation Toolkit with ready-to-use scripts for invoicing, reporting, data pipelines, and more.

Get the Python Business Automation Toolkit ($9)

Templates for invoices, email reports, file organization, database queries, and 20+ more automations.

Top comments (0)