Docker & Containerization

Docker Compose for Local Development

35 min

Real apps need several services. Docker Compose describes them in one file and starts them together.

compose.yaml

services:
  web:
    build: .
    command: flask --app run.py run --host 0.0.0.0 --port 8000 --debug
    ports: ["8000:8000"]
    env_file: .env
    environment:
      DATABASE_URL: postgresql://app:app@db:5432/app
      REDIS_URL: redis://redis:6379/0
    volumes:
      - .:/app                 # live code reload in development
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_started

  db:
    image: postgres:16
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: app
      POSTGRES_DB: app
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app"]
      interval: 5s
      retries: 10

  redis:
    image: redis:7-alpine

volumes:
  pgdata:

Commands

docker compose up -d --build        # build and start everything
docker compose logs -f web          # follow one service's logs
docker compose exec web flask --app run.py db upgrade
docker compose exec db psql -U app  # open a database shell
docker compose down                 # stop (data volume kept)
docker compose down -v              # stop and DELETE volumes (data gone)

Networking

Services reach each other by service name: the app connects to db:5432, not localhost. Inside a container, localhost means the container itself.

Volumes

  • Named volumes (pgdata) persist data between restarts.
  • Bind mounts (.:/app) share your source code for live reload in development. Do not use them in production.

Development vs production

Keep one compose file for development, and override settings for other uses with compose.override.yaml or -f compose.prod.yaml. Many teams use Compose only locally and deploy the same image to a platform.

Exercise

Write a compose file for your Flask app with PostgreSQL (with a health check) and Redis. Run migrations through docker compose exec, confirm data survives down/up, and see what down -v does.

Check yourself

  • Why does the app connect to db instead of localhost?
  • What is the difference between a named volume and a bind mount?
  • What does depends_on with service_healthy add?

I tuoi progressi sono salvati solo in questo browser.

Invia per la revisione (10 punti)