Docker Compose for Beginners: Orchestrating Your First Stack
Running docker run is fine for one container. But what if you have a Node.js API, a Postgres database, and a Redis cache?
Advertisement
The Problem
You have to run three separate commands, manage three separate networks, and restart them individually if they crash.
The Solution: docker-compose.yml
This file describes your entire "Stack". It's Infrastructure as Code.
version: '3.8'
services:
# 1. Your Custom App
api:
build: .
ports:
- "3000:3000"
environment:
- DB_HOST=postgres
- REDIS_HOST=redis
depends_on:
- postgres
- redis
# 2. The Database
postgres:
image: postgres:15
environment:
POSTGRES_PASSWORD: secretpassword
volumes:
- pgdata:/var/lib/postgresql/data
# 3. The Cache
redis:
image: redis:alpine
# 4. Persistent Storage
volumes:
pgdata:
How to Run It
docker-compose up -d
That's it. Docker will:
- Pull the Postgres and Redis images.
- Build your Node.js app (
build: .). - Create a shared network so
apican talk topostgresjust by using the hostname "postgres". - Start everything in the background (
-dmeans detached).
Persistence (Volumes)
See that volumes section? That ensures that even if you delete the Postgres container, your database files persist in pgdata. If you omit this, you lose all your data when the container stops!
Networking Magic
In Docker Compose, service names utilize internal DNS. Inside the api container, ping postgres works. You don't need IP addresses.
Advertisement
Quiz
What does the 'depends_on' key do in Docker Compose?
Conclusion
Docker Compose is the bridge between "it works on my machine" and "it works in production". It documents your infrastructure dependencies explicitly, preventing the "you forgot to install Redis" error.
Md Nasim Sheikh
Software Developer at softexForge