Module 5 Lesson 2: Your First docker-compose.yml
·DevOps

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:

  1. Indentation: Use 2 spaces. Do NOT use Tabs. If your indentation is wrong, the file won't run.
  2. Colons: There is always a space after a colon (image: redis).
  3. 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?

  1. Docker created a network just for this folder.
  2. Docker pulled nginx and redis.
  3. Docker started both containers.
  4. 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

  1. Create a docker-compose.yml file with two services: proxy (using nginx) and cache (using redis).
  2. Map port 80 of the host to port 80 of proxy.
  3. Run docker-compose up -d.
  4. Run docker-compose ps. Are both services Up?
  5. Try to run docker stop on one of the containers manually. Then run docker-compose up -d again. 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.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn