화. 8월 12th, 2025

G: 🚀 Welcome, fellow developers and DevOps enthusiasts!

Docker has revolutionized how we build, ship, and run applications. But what happens when your application isn’t just one container, but a collection of inter-connected services like a web server, a database, and a caching layer? That’s where Docker Compose steps in!

Docker Compose is a fantastic tool that simplifies the management of multi-container Docker applications. Instead of running multiple docker run commands and manually setting up networks and volumes, you define your entire application stack in a single docker-compose.yml file. Then, with a single command, you can spin up, scale, and manage all your services. ✨

This guide will be your ultimate cheat sheet for the most essential Docker Compose commands. We’ll cover everything you need to know for day-to-day development, testing, and even production deployments. Let’s dive in!


Understanding the Heart: docker-compose.yml

Before we jump into commands, it’s crucial to understand that Docker Compose relies on a configuration file, typically named docker-compose.yml (or docker-compose.yaml). This file describes your application’s services, networks, and volumes in a human-readable YAML format.

Here’s a simple example of a docker-compose.yml for a basic web application with a Node.js backend and a PostgreSQL database:

version: '3.8' # Specify the Compose file format version

services:
  web:
    build: . # Build the image from the current directory (where Dockerfile is)
    ports:
      - "3000:3000" # Map host port 3000 to container port 3000
    volumes:
      - .:/app # Mount the current directory into /app inside the container
    depends_on:
      - db # Ensure db starts before web
    environment:
      DATABASE_URL: postgres://user:password@db:5432/mydatabase
    networks:
      - app-network

  db:
    image: postgres:13 # Use the PostgreSQL 13 image from Docker Hub
    environment:
      POSTGRES_DB: mydatabase
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password
    volumes:
      - db-data:/var/lib/postgresql/data # Persistent data for the database
    networks:
      - app-network

volumes:
  db-data: # Define a named volume for persistent database storage

networks:
  app-network: # Define a custom network for services to communicate on

(Remember to save this file as docker-compose.yml in your project’s root directory!)


I. Essential Lifecycle Commands: Getting Your Services Up and Running (and Down!)

These are the commands you’ll use most frequently to control the life of your multi-container applications.

1. docker-compose up: Build, Create, Start Services 🚀

This is your go-to command for bringing your entire application stack online. It performs several actions:

  • It builds (if build is specified in docker-compose.yml) or pulls (if image is specified) the necessary images.

  • It creates the containers, networks, and volumes as defined.

  • It starts all the services.

  • Syntax: docker-compose up [OPTIONS] [SERVICE...]

  • Common Usages:

    • docker-compose up: Starts all services in the foreground, showing their logs. Press Ctrl+C to stop them (gracefully).
    • docker-compose up -d: (Most Common) Starts all services in “detached” mode (in the background). Your terminal will be free.
      docker-compose up -d
      # Output:
      # Creating network "myproject_app-network" with the default driver
      # Creating volume "myproject_db-data" with default driver
      # Creating myproject_db_1 ... done
      # Creating myproject_web_1 ... done
    • docker-compose up --build: Forces Docker Compose to rebuild images even if they already exist (useful after changing your Dockerfile).
      docker-compose up -d --build
    • docker-compose up --force-recreate: Forces recreation of containers, even if their configuration hasn’t changed.
      docker-compose up -d --force-recreate
    • docker-compose up --no-deps [SERVICE]: Starts a specific service without its dependencies. Be careful with this!
      docker-compose up -d --no-deps web

2. docker-compose down: Stop and Remove Services 🛑

This command stops and removes all containers, networks, and (by default) the default network created by up. It’s the clean way to shut down your entire Compose project.

  • Syntax: docker-compose down [OPTIONS]

  • Common Usages:

    • docker-compose down: Stops and removes containers and the default network.
      docker-compose down
      # Output:
      # Stopping myproject_web_1 ... done
      # Stopping myproject_db_1 ... done
      # Removing myproject_web_1 ... done
      # Removing myproject_db_1 ... done
      # Removing network myproject_app-network
    • docker-compose down --volumes or docker-compose down -v: (Highly Recommended for Cleanups) Removes named volumes declared in the volumes section of your docker-compose.yml (like db-data in our example) and anonymous volumes. This is crucial for truly clean restarts, especially during development.
      docker-compose down -v
    • docker-compose down --rmi all: Removes all images used by any service. Use with caution!
      docker-compose down --rmi all

3. docker-compose start: Resume Stopped Services ▶️

If you’ve stopped services using docker-compose stop (or they crashed), this command will restart them without recreating them.

  • Syntax: docker-compose start [SERVICE...]

  • Example:

    docker-compose start web db
    # Output:
    # Starting myproject_web_1 ... done
    # Starting myproject_db_1 ... done

4. docker-compose stop: Stop Running Services ⏸️

This command stops running services without removing their containers. This means you can start them again later, and their state will be preserved.

  • Syntax: docker-compose stop [SERVICE...]

  • Example:

    docker-compose stop web
    # Output:
    # Stopping myproject_web_1 ... done

5. docker-compose restart: Stop and Start Services 🔄

A convenient command to stop and then start all or specified services. Useful for applying configuration changes that don’t require rebuilding.

  • Syntax: docker-compose restart [SERVICE...]

  • Example:

    docker-compose restart
    # Output:
    # Restarting myproject_web_1 ... done
    # Restarting myproject_db_1 ... done

6. docker-compose build: Build or Rebuild Service Images 🏗️

Use this command to manually build or rebuild images for your services before running them with docker-compose up. This is useful if you’ve made changes to your Dockerfile and want to ensure the latest image is ready.

  • Syntax: docker-compose build [OPTIONS] [SERVICE...]

  • Common Usages:

    • docker-compose build: Builds images for all services that have a build instruction.
      docker-compose build
    • docker-compose build --no-cache [SERVICE]: Builds a specific service’s image without using the Docker build cache. Useful for ensuring a fresh build.
      docker-compose build --no-cache web

II. Inspection and Debugging Commands: Peeking Inside Your Containers

When things go wrong (and they will!), these commands are invaluable for understanding what’s happening within your Docker Compose services.

1. docker-compose ps: List Services and Their Status 🔍

This command lists all the services defined in your docker-compose.yml along with their current state, ports, and command.

  • Syntax: docker-compose ps [OPTIONS]

  • Example:

    docker-compose ps
    # Output:
    #      Name                    Command               State           Ports
    # --------------------------------------------------------------------------------
    # myproject_db_1    docker-entrypoint.sh postgres   Up      5432/tcp
    # myproject_web_1   docker-entrypoint.sh npm start  Up      0.0.0.0:3000->3000/tcp

2. docker-compose logs: View Service Logs 📜

See the output (STDOUT/STDERR) of your services. Crucial for debugging applications that aren’t starting correctly or are throwing errors.

  • Syntax: docker-compose logs [OPTIONS] [SERVICE...]

  • Common Usages:

    • docker-compose logs: Shows logs from all services.
      docker-compose logs
    • docker-compose logs -f [SERVICE]: (Very Common) Follows (streams) the logs of a specific service in real-time. Press Ctrl+C to stop following.
      docker-compose logs -f web
    • docker-compose logs --tail 50 [SERVICE]: Shows only the last 50 lines of logs for a service.
      docker-compose logs --tail 50 db
    • docker-compose logs --timestamps: Adds timestamps to log output.
      docker-compose logs --timestamps web

3. docker-compose exec: Execute a Command in a Running Container 💻

This is like SSHing into a running container. You can run arbitrary commands inside a service’s container.

  • Syntax: docker-compose exec [OPTIONS] SERVICE COMMAND [ARGS...]

  • Common Usages:

    • docker-compose exec web bash: Get an interactive shell (Bash) inside the web service container. If bash isn’t available, try sh.
      docker-compose exec web bash
      # Now you are inside the container:
      # root@container_id:/app# ls -la
      # root@container_id:/app# exit
    • docker-compose exec db psql -U user_name mydatabase: Connect to the PostgreSQL database inside the db container using the psql client.
      docker-compose exec db psql -U user mydatabase
    • docker-compose exec web npm test: Run tests inside the web service container.
      docker-compose exec web npm test

4. docker-compose run: Run a One-Off Command 🏃‍♂️

Similar to exec, but run creates a new container for the command and usually removes it after the command finishes (if --rm is used). This is ideal for one-off tasks like database migrations, cron jobs, or installing dependencies.

  • Syntax: docker-compose run [OPTIONS] SERVICE COMMAND [ARGS...]

  • Common Usages:

    • docker-compose run --rm web npm install: Create a new web service container, run npm install, and then remove the container. Very useful for fresh installs or quick actions.
      docker-compose run --rm web npm install
    • docker-compose run --rm db psql -U user mydatabase -c "SELECT * FROM users;": Run a single SQL query against the database from a new db container.
      docker-compose run --rm db psql -U user mydatabase -c "SELECT * FROM users;"
    • docker-compose run --entrypoint bash web: Override the service’s default entrypoint and run bash instead.
      docker-compose run --rm --entrypoint bash web

III. Utility and Management Commands: Beyond the Basics

These commands offer more control over your Docker Compose environment and help with maintenance.

1. docker-compose pull: Pull Service Images ⬇️

Downloads (pulls) the latest images for all services (or specific ones) from Docker Hub or your configured registry. This doesn’t start or build anything; it just pre-fetches images.

  • Syntax: docker-compose pull [SERVICE...]

  • Example:

    docker-compose pull
    # Output:
    # Pulling db (postgres:13)...
    # Pulling fs-web (my-web-app:latest)...
    # Download complete.

2. docker-compose images: List Images Used by Services 🖼️

Shows the images associated with the services in your docker-compose.yml.

  • Syntax: docker-compose images

  • Example:

    docker-compose images
    # Output:
    #     Container           Repository       Tag      Image Id      Size
    # ----------------------------------------------------------------------
    # myproject_db_1        postgres          13       abcdef123456   234MB
    # myproject_web_1     myproject_web    latest     fedcba987654   150MB

3. docker-compose rm: Remove Stopped Service Containers 🗑️

Removes stopped service containers. This is useful for cleaning up after failed starts or stop commands.

  • Syntax: docker-compose rm [OPTIONS] [SERVICE...]

  • Common Usages:

    • docker-compose rm: Prompts you to confirm removal of all stopped containers.
      docker-compose rm
      # Output:
      # Going to remove myproject_web_1
      # Are you sure? [yN] y
      # Removing myproject_web_1 ... done
    • docker-compose rm -f: Forces removal without a confirmation prompt.
      docker-compose rm -f db

4. docker-compose config: Validate and View Configuration ✅

Checks your docker-compose.yml file for syntax errors and displays the final, merged configuration. This is extremely useful for debugging configuration issues, especially when using multiple Compose files.

  • Syntax: docker-compose config [OPTIONS]

  • Common Usages:

    • docker-compose config: Validates and prints the full configuration.
      docker-compose config
    • docker-compose config -q: Quiet mode. Only checks for validity and returns an exit code (0 for valid, non-zero for error). Great for scripting.
      docker-compose config -q && echo "Compose file is valid!"
    • docker-compose config --services: Lists all service names.
      docker-compose config --services
      # Output:
      # web
      # db

5. docker-compose top: Display Running Processes 📊

Shows the running processes within the containers of your services, similar to the top command on a Linux system.

  • Syntax: docker-compose top [SERVICE...]

  • Example:

    docker-compose top
    # Output:
    # myproject_db_1
    # PID    USER    TIME    COMMAND
    # 1      postgres  0:00    postgres
    # 15     postgres  0:00    postgres: checkpointer
    # ...
    
    # myproject_web_1
    # PID    USER    TIME    COMMAND
    # 1      node      0:00    node server.js

6. docker-compose version: Show Version Information ℹ️

Displays the Docker Compose version and Docker Engine version information. Useful for checking compatibility or reporting issues.

  • Syntax: docker-compose version

  • Example:

    docker-compose version
    # Output:
    # Docker Compose version v2.20.2
    # Docker Engine:
    #  Version: 24.0.5
    #  API Version: 1.43
    #  Go Version: go1.20.6
    #  Git Commit: 1d633aa
    #  Built: Mon Aug 14 17:39:10 2023
    #  OS/Arch: linux/amd64

7. docker compose ls: List Compose Projects (Newer CLI) 📁

Important Note: Docker Compose has evolved! While docker-compose (with a hyphen) refers to the standalone Python-based tool, docker compose (with a space) is now integrated directly into the Docker CLI. Many newer Docker installations come with docker compose as the default. The commands are largely the same, but you’ll use docker compose instead of docker-compose.

docker compose ls (note the space) lists active Compose projects.

  • Syntax: docker compose ls [OPTIONS]

  • Example:

    docker compose ls
    # Output:
    # NAME         STATUS    CONFIG FILES
    # myproject    running   docker-compose.yml

    (You might not find docker-compose ls with the hyphenated version, as this is a feature of the newer integrated CLI.)


IV. Real-World Tips & Best Practices for Docker Compose

  • Using Multiple Compose Files (-f): For different environments (development, testing, production), you can use multiple docker-compose.yml files. Docker Compose intelligently merges them.

    • docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d
    • This is great for overriding settings, e.g., using different image tags or more robust configurations for production.
  • Environment Variables (.env): Keep sensitive information (like database passwords) out of your docker-compose.yml by using environment variables. Docker Compose automatically loads variables from a .env file in the same directory.

    • Create a .env file: POSTGRES_PASSWORD=mysecretpassword
    • Reference in docker-compose.yml: environment: - POSTGRES_PASSWORD
  • Specify Project Name (-p): Docker Compose automatically derives a project name from the directory. You can override this using the -p flag, which helps when running multiple Compose projects in parallel or just for clearer naming.

    • docker-compose -p mywebapp up -d (Containers will be named mywebapp_web_1, mywebapp_db_1, etc.)
  • Persistent Data (Volumes): Always use named volumes (as shown in our example with db-data) for databases and other persistent data to ensure your data isn’t lost when containers are removed.

  • Mind the Hyphen vs. Space: As mentioned, remember the distinction between docker-compose (older, standalone) and docker compose (newer, integrated). If you have a recent Docker Desktop or Docker Engine installation, docker compose is likely what you’ll use. Both largely share the same command syntax.

  • Resource Limits (Production): For production environments, consider adding resource limits to your services in the docker-compose.yml to prevent a single service from consuming all available host resources.

    services:
      web:
        deploy:
          resources:
            limits:
              cpus: '0.5' # 0.5 CPU core
              memory: 512M # 512 MB of memory
  • Health Checks: Ensure your services are truly “up” and responsive, not just running. Docker Compose supports health checks.

    services:
      web:
        healthcheck:
          test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
          interval: 30s
          timeout: 10s
          retries: 3

Conclusion ✨

Docker Compose is an incredibly powerful and user-friendly tool for orchestrating multi-container applications. By mastering these essential commands, you’ll gain confidence in deploying, managing, and debugging your services. From bringing up your entire stack with docker-compose up -d to debugging with docker-compose logs -f and docker-compose exec, you now have the practical knowledge to tackle common scenarios.

Keep experimenting, refer to the official Docker Compose documentation, and happy containerizing! Your development workflow just got a whole lot smoother. 🚀

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다