Docker Mastery Part 3: Orchestrating Services with Docker Compose

Stop running individual commands. Learn how to define and run multi-container applications using Docker Compose.

FSI
Full Stack Insights
2 min read...

Introduction

Running docker run commands manually for a complex application with a database, cache, and frontend is tedious and error-prone. Enter Docker Compose.

1. What is Docker Compose?

Docker Compose is a tool for defining and running multi-container Docker applications. You use a YAML file to configure your application's services, network, and volumes.

2. The docker-compose.yml File

Here is an example structure for a Node.js app connected to a Redis cache:

version: '3.8'

services:
  web:
    build: .
    ports:
      - "8080:3000"
    environment:
      - REDIS_HOST=redis
    depends_on:
      - redis

  redis:
    image: "redis:alpine"
    volumes:
      - redis-data:/data

volumes:
  redis-data:

Key Elements:

  • Services: The distinct containers (e.g., web, redis).
  • Build: Tells Docker to build the image from the current directory's Dockerfile.
  • Ports: Maps host ports to container ports.
  • Depends_on: Controls startup order.
  • Volumes: Persists data (discussed in Part 5).

3. Basic Commands

docker-compose up

Builds, (re)creates, starts, and attaches to containers for a service.

# Start in detached mode
docker-compose up -d

# Force a build even if images exist
docker-compose up -d --build

docker-compose down

Stops containers and removes containers, networks, volumes, and images created by up.

docker-compose down

docker-compose ps

Lists containers specific to the current compose file.

docker-compose logs

View logs for the stack.

# View logs for a specific service
docker-compose logs -f web

Summary

Docker Compose is essential for local development environments. It codifies your infrastructure, ensuring that git clone and docker-compose up is all a new developer needs to start working. In Part 4: Real-World Scenarios, we will apply this to build a full-stack app.

Share this article:

Related Articles

FSI

Full Stack Insights

Software Engineer

Passionate about software development, architecture, and sharing knowledge with the community.