Docker — Containers, Images & Dockerfile
Docker — Containers, Images & Dockerfile
🎯 What you'll be able to do after this lesson
After completing this lesson, you'll be confident doing all three of the following.
- ▸✅ Docker's 4 core elements: images, containers, volumes, and networks
- ▸✅ Dockerfile multi-stage builds + alpine
- ▸✅ docker-compose for multi-container setups (DB + Redis + app)
Keep the learning objectives as a checklist, and close the lesson once you can answer all of them.
Docker vs VM + Core Concepts
One-liner: VM = renting an entire house, container = renting a single room. They share the same OS kernel and consume fewer resources.
Core concepts:
Dockerfile + Multi-Stage Builds
Dockerfile — image build specification:
Key instructions:
Optimization tips:
- ▸COPY frequently-changing files last (improves cache ↑)
- ▸Use
.dockerignoreto excludenode_modulesand.git - ▸Multi-stage builds — exclude build tools to produce a smaller image
- ▸Prefer Alpine base (5 MB); fall back to distroless if compatibility issues arise
Docker Compose — Spin Up Your Local Dev Environment in One Go
Limitations of running containers one by one
5 commands + manual network wiring — complex and error-prone.
docker-compose.yml — one file does it all
3 containers + network + volume — all brought up with a single command.
Automatic Networking
Compose places all services on a single shared network. Each service name becomes a hostname:
Use the service name, not localhost. Cleaner than the old --link approach.
Environment Variables — Automatic .env Loading
Running compose up automatically reads the .env file and substitutes values. Don't forget to add .env to .gitignore.
Volumes — Data Persistence
Data persists even after the container is deleted. Running down won't remove it — only down -v will explicitly delete it.
healthcheck + depends_on (modern approach)
depends_on alone only guarantees startup order — it doesn't guarantee that the DB is actually ready to accept connections. Combining it with a healthcheck is the standard practice.
Don't use Compose alone in production
- ▸Compose is the standard for local and development environments
- ▸Production uses Kubernetes, ECS, Cloud Run, etc.
- ▸Tools like Kompose can convert Compose files directly into Kubernetes manifests
🤖 Try asking AI for help like this
- ▸"Create a docker-compose.yml that runs PostgreSQL, Redis, and a Node.js app together"
- ▸"Add healthcheck and conditional depends_on to this compose file"
- ▸"Separate the environment variables into a .env file"