Quay lại TIL
2023-03-10Devopsbeginner4 min

Getting Started with Docker Compose


# Getting Started with Docker Compose

Today I learned how to use Docker Compose to simplify the development and deployment of multi-container applications.

## The Problem with Multiple Containers

Before using Docker Compose, I was managing multiple containers manually with individual docker run commands. This approach had several drawbacks:
- Complex startup scripts with many command-line arguments
- No easy way to define container dependencies and startup order
- Difficulty sharing configurations across team members
- Tedious network configuration to enable container communication

## Docker Compose Solution

Docker Compose solves these problems by allowing you to define your entire application stack in a single YAML file (docker-compose.yml).

## Key Concepts I Learned

- **Services**: Definitions for each container in your application
- **Networks**: How containers communicate with each other
- **Volumes**: Persistent data storage that survives container restarts
- **Environment Variables**: Configuration that can change between environments
- **Dependencies**: Controlling the order in which containers start

## My First Compose File

I created a simple web application with a frontend, backend API, and database. The compose file defined all three services, their connections, and configuration.

## Benefits Realized

- **Simplified Development**: One command (docker-compose up) to start the entire stack
- **Consistent Environments**: Everyone on the team uses the exact same configuration
- **Easy Onboarding**: New developers can get started without complex setup instructions
- **Version Control**: Infrastructure configuration stored alongside application code

This approach has significantly streamlined our development workflow and reduced environment-related issues.

Code Example

version: '3.8'

services:
  frontend:
    build: ./frontend
    ports:
      - "3000:3000"
    depends_on:
      - backend
    environment:
      - API_URL=http://backend:8000

  backend:
    build: ./backend
    ports:
      - "8000:8000"
    depends_on:
      - database
    environment:
      - DB_HOST=database
      - DB_USER=postgres
      - DB_PASSWORD=example
      - DB_NAME=myapp

  database:
    image: postgres:13
    volumes:
      - db-data:/var/lib/postgresql/data
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=example
      - POSTGRES_DB=myapp

volumes:
  db-data:
DockerDocker ComposeContainers