DevOpsDockerContainersTutorial

Docker Compose for Beginners: Orchestrating Your First Stack

3.32 min read
Md Nasim SheikhMd Nasim Sheikh
Share:

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:

  1. Pull the Postgres and Redis images.
  2. Build your Node.js app (build: .).
  3. Create a shared network so api can talk to postgres just by using the hostname "postgres".
  4. Start everything in the background (-d means 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

Quick 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
Written by

Md Nasim Sheikh

Software Developer at softexForge

Verified Author150+ Projects
Published:

You May Also Like