Unit 3: Networking, Volumes & Docker Compose
Part G: Volumes, Storage & Networking
1. Volumes (Persistent Data)
Named volumes are Docker-managed persistent stores. A container can be deleted/recreated while important database data remains safe.
docker volume create mydata
docker run -d --name db -v mydata:/data IMAGE
Hinglish: Production data ko container ki writable layer par depend mat karo; persistent storage/volumes use karo.
2. Bind Mounts
A bind mount maps a host path/file into a container. It is useful for local development to sync code.
docker run -it --rm -v ${PWD}:/app IMAGE sh
3. Port Mapping & The localhost Rule
Syntax is -p HOST_PORT:CONTAINER_PORT. Example -p 8080:80 means host 8080 forwards to container 80.
Inside a container, 'localhost' means that same container. If your app and database are separate containers, the app must connect using the database's service/container name (e.g., 'db'), NOT 'localhost'.
Part H: Docker Compose Complete
Compose defines multi-container applications in YAML (compose.yaml) and manages services, networks, and volumes together.
1. Master compose.yaml
services:
app:
build: .
ports:
- "8000:8000"
environment:
DB_HOST: db
DB_PORT: "5432"
depends_on:
- db
db:
image: postgres:16
environment:
POSTGRES_DB: appdb
POSTGRES_USER: appuser
POSTGRES_PASSWORD: change-me
volumes:
- db_data:/var/lib/postgresql/data
volumes:
db_data:
Compose services on the same network can discover each other by service name (e.g., DB_HOST: db).
2. Compose Commands
docker compose up -d(Start in background)docker compose down(Stop and remove containers/networks)docker compose logs -f(Tail logs)docker compose exec app sh(Open shell in app service)
Compose Data Warning:
docker compose down -v will remove named volumes and therefore delete your database data. Never use it casually!Part I: Environment Variables & Secrets
1. Environment Variables
Use -e KEY=value for one variable or --env-file .env for a file.
docker run -e APP_ENV=dev my-app:1.0
2. Secrets Security
Hinglish: Secrets (passwords, API keys) Dockerfile mein hard-code mat karo! Use environment variables injected at runtime, or proper secret-management mechanisms.