Module 5 Lesson 2: Your First docker-compose.yml
Hands-on with YAML. Learn the structure of a Compose file and build a working stack with a web server and a database in minutes.
Module 5 Lesson 2: Your First docker-compose.yml
Let's build a classic "Web + Database" stack. We will use nginx for the web and redis for the data.
1. The Anatomy of a Compose File
Create a file named docker-compose.yml in a new folder.
version: "3.8" # Recommended version
services: # Containers are defined as 'services'
frontend: # Name of the service
image: nginx
ports:
- "8080:80"
backend: # Another service
image: redis
restart: always
Key Rules of YAML:
- Indentation: Use 2 spaces. Do NOT use Tabs. If your indentation is wrong, the file won't run.
- Colons: There is always a space after a colon (
image: redis). - Lists: Items in a list start with a hyphen (
- "8080:80").
2. Launching the Stack
Navigate to the folder in your terminal and run:
docker-compose up -d
up: Tells Compose to create and start all services.-d: Detached mode (runs in the background).
What happened?
- Docker created a network just for this folder.
- Docker pulled
nginxandredis. - Docker started both containers.
- Docker linked them together.
Visualizing the Process
graph TD
Start[Input] --> Process[Processing]
Process --> Decision{Check}
Decision -->|Success| End[Complete]
Decision -->|Retry| Process
3. Image vs. Build
Sometimes you want to build an image from a Dockerfile instead of using a pre-made one from Hub.
services:
app:
build: . # Build the Dockerfile in the current directory
ports:
- "3000:3000"
4. The depends_on Instruction
If your web app will crash if the database isn't running yet, use depends_on.
services:
web:
build: .
depends_on:
- db
db:
image: postgres
Note: This only ensures the db container HAS STARTED. It doesn't guarantee the database inside is actually "Ready" to accept connections yet.
Exercise: The Redis Counter
- Create a
docker-compose.ymlfile with two services:proxy(usingnginx) andcache(usingredis). - Map port
80of the host to port80ofproxy. - Run
docker-compose up -d. - Run
docker-compose ps. Are both servicesUp? - Try to run
docker stopon one of the containers manually. Then rundocker-compose up -dagain. What does Compose do? (Does it restart the whole stack or only the missing one?)
Summary
You’ve moved from "One-line commands" to "Declarative Infrastructure." You can now describe an entire system in a single text file. This is the foundation of Infrastructure as Code (IaC).
Next Lesson: Persistent data and private talks: Services, networks, and volumes in Compose.