Docker Compose – Multi Container Applications

Docker Compose – Multi Container Applications

When building real applications, you need:

  • Django

  • PostgreSQL

  • Redis

  • Celery

Managing multiple containers manually is hard.

Enter Docker Compose

Docker Compose allows defining multi-container applications using YAML.

Example docker-compose.yml

version: "3.9"

services:
web:
build: .
command: gunicorn project.wsgi:application --bind 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
depends_on:
- db

db:
image: postgres:15
environment:
POSTGRES_DB: mydb
POSTGRES_USER: myuser
POSTGRES_PASSWORD: mypassword

Run Compose

docker-compose up --build

Docker Volumes & Networks

Volumes

Used for:

  • Persisting database data

  • Sharing files

docker volume create myvolume

Networks

Docker automatically creates bridge networks, but you can create custom ones:

docker network create mynetwork

Docker for Production (Best Practices)

Security Best Practices

  • Use official base images

  • Use specific version tags

  • Avoid running as root

  • Use .dockerignore

  • Keep images small

Multi-Stage Builds

FROM python:3.12 as builder

WORKDIR /app
COPY requirements.txt .
RUN pip install --user -r requirements.txt

FROM python:3.12-slim
WORKDIR /app
COPY --from=builder /root/.local /root/.local
COPY . .

CMD ["python", "app.py"]

Docker + CI/CD

Docker works perfectly with:

  • GitHub Actions

  • GitLab CI/CD

  • Jenkins

Example flow:

  1. Push code

  2. Build Docker image

  3. Push to Docker Hub

  4. Deploy to server

Docker in Cloud Deployment

Docker can be deployed to:

  • Amazon ECS

  • Kubernetes

  • Google Kubernetes Engine

  • Azure Kubernetes Service



Comments

Popular posts from this blog

Database Integration in FastAPI (SQLAlchemy CRUD)

Middleware & CORS in FastAPI

Python Data Handling