G: Are you diving into the world of Docker and finding yourself managing multiple containers one by one? 😩 It can get messy, right? That’s where Docker Compose comes to your rescue! 🚀
Docker Compose is a powerful tool that helps you define and run multi-container Docker applications. With a single YAML file (docker-compose.yml
), you can configure all your application’s services, networks, and volumes, and then spin them all up with just one command! Think of it as your application’s blueprint and an easy-to-use remote control.
This cheatsheet is designed specifically for beginners, covering the most frequently used Docker Compose commands that will streamline your development workflow. Let’s get started! ✨
What is Docker Compose and Why Use It? 🤔
At its core, Docker Compose allows you to:
- Define Services: Specify different parts of your application (e.g., a web server, a database, a caching layer) and how they relate to each other.
- Orchestrate: Start, stop, and manage all these services together as a single unit.
- Simplify Development: Replicate your production environment locally with ease.
- Ensure Consistency: Your entire team can use the exact same setup.
Note on docker-compose
vs docker compose
:
You might see docker-compose
(with a hyphen) and docker compose
(with a space). Both generally work for most common commands. docker compose
(with a space) is the newer, integrated Docker CLI plugin. For this cheatsheet, we’ll primarily use docker-compose
as it’s widely compatible and what many beginners first encounter, but feel free to substitute with docker compose
if you prefer!
The Heart of Compose: docker-compose.yml
File ❤️
Before we dive into commands, let’s quickly understand the docker-compose.yml
file. This YAML file is where you define your services. Here’s a common example of a simple web application with a database:
# docker-compose.yml
version: '3.8' # Specifies the Compose file format version
services:
web: # Define a service named 'web'
build: . # Build the image from the Dockerfile in the current directory
ports:
- "80:80" # Map host port 80 to container port 80
depends_on:
- db # Ensure 'db' service starts before 'web'
environment:
DATABASE_URL: postgres://user:password@db:5432/mydatabase # Environment variables for the 'web' service
db: # Define a service named 'db'
image: postgres:13 # Use the official Postgres 13 image from Docker Hub
environment:
POSTGRES_DB: mydatabase
POSTGRES_USER: user
POSTGRES_PASSWORD: password
volumes:
- db-data:/var/lib/postgresql/data # Persist database data to a named volume
volumes:
db-data: # Define the named volume for persistent data
Key Sections:
version
: Specifies the Compose file format version. Always use the latest stable one (e.g., ‘3.8’, ‘3.9’).services
: Defines all the containers (services) that make up your application. Each service has configurations likebuild
,image
,ports
,volumes
,environment
,depends_on
, etc.volumes
: Defines named volumes for persistent data storage, ensuring your data isn’t lost when containers are removed.networks
(optional, but useful): Defines custom networks for your services. Compose creates a default network for your services if you don’t specify one.
Docker Compose Commands Cheatsheet! 📋
Make sure you are in the same directory as your docker-compose.yml
file when running these commands.
I. Getting Started: The Essentials 🚀
These are the commands you’ll use most often to start and stop your application.
-
docker-compose up
: Build, create, and start your services.- This is your go-to command to bring your entire application online.
- If images aren’t found, it will try to build them (if
build:
is specified) or pull them from Docker Hub (ifimage:
is specified). - It will show container logs directly in your terminal.
docker-compose up # Start all services in the foreground
- 💡 Pro-Tip: Use the
-d
(detached) flag to run services in the background. This frees up your terminal.
docker-compose up -d # Start all services in the background (detached mode)
-
docker-compose down
: Stop and remove containers, networks, and volumes (optional).- This is the clean way to shut down your entire Compose application.
- It stops all running services and removes the containers and the default network created by
up
.
docker-compose down # Stop and remove services and default network
- 🧹 Pro-Tip: Use
--volumes
to remove named volumes declared in thevolumes
section of yourdocker-compose.yml
. Be careful! This will delete your persistent data. Only use it when you want a completely fresh start.
docker-compose down --volumes # Stop and remove services, network, AND named volumes
-
docker-compose start [service...]
: Start existing stopped services.- If you’ve previously run
docker-compose up
and thendocker-compose stop
, this command will bring them back online without rebuilding or recreating them.
docker-compose start # Start all stopped services in the project docker-compose start web # Start only the 'web' service
- If you’ve previously run
-
docker-compose stop [service...]
: Stop running services without removing them.- This pauses your application but keeps the containers and their data intact. You can
start
them again later.
docker-compose stop # Stop all running services docker-compose stop db # Stop only the 'db' service
- This pauses your application but keeps the containers and their data intact. You can
-
docker-compose restart [service...]
: Restart services.- A handy command to quickly restart one or all services, useful after making configuration changes or to clear up issues.
docker-compose restart # Restart all services docker-compose restart web # Restart only the 'web' service
II. Inspecting & Managing Running Services 👀
Once your services are up and running, you’ll need ways to check their status and interact with them.
-
docker-compose ps
: List services and their status.- Shows a snapshot of your services: their names, commands, status, and exposed ports.
docker-compose ps
Example Output:
Name Command State Ports --------------------------------------------------------------------- myproject_db_1 docker-entrypoint.sh postgres Up 5432/tcp myproject_web_1 /bin/sh -c npm start Up 0.0.0.0:80->80/tcp
-
docker-compose logs [service...]
: View output logs from services.- Essential for debugging! See what your application is printing to its standard output and error streams.
docker-compose logs web # Show logs for the 'web' service docker-compose logs -f # Follow (stream) logs from all services in real-time docker-compose logs --tail 100 web # Show the last 100 lines of logs for 'web'
-
docker-compose exec [service] [command]
: Execute a command in a running service container.- This is incredibly useful for debugging or running one-off commands inside a specific container, like accessing a database shell or checking files.
docker-compose exec web bash # Open a bash shell inside the 'web' container docker-compose exec db psql -U user mydatabase # Connect to the Postgres database docker-compose exec web ls -l /app # List files in /app directory inside 'web' container
III. Building & Pulling Images 🏗️
These commands help you manage the Docker images your services depend on.
-
docker-compose build [service...]
: Build or rebuild services.- If your
docker-compose.yml
specifies abuild:
context (pointing to aDockerfile
), this command will build the Docker image for that service. - Useful when you make changes to your
Dockerfile
or the code it copies.
docker-compose build web # Build the image for the 'web' service docker-compose build # Build images for all services that have a 'build' instruction
- If your
-
docker-compose pull [service...]
: Pull service images.- If your
docker-compose.yml
specifies animage:
(e.g.,postgres:13
), this command will download (pull) the latest version of that image from Docker Hub or your configured registry.
docker-compose pull db # Pull the 'db' service image docker-compose pull # Pull all service images
- If your
IV. Cleaning Up & Maintenance 🧹
Sometimes you need to get rid of old containers or validate your configuration.
-
docker-compose rm [service...]
: Remove stopped service containers.- This command removes containers that are no longer running. Use
docker-compose down
for a more comprehensive cleanup.
docker-compose rm web # Remove the 'web' service container if it's stopped
- This command removes containers that are no longer running. Use
-
docker-compose config
: Validate and view the Compose configuration.- This command checks your
docker-compose.yml
file for syntax errors and displays the final, merged configuration. Incredibly useful for debugging YAML issues!
docker-compose config # Validate and show the full configuration docker-compose config --services # List only the service names defined in the config
- This command checks your
V. Other Useful Commands (Quick Mentions) ⚡
-
docker-compose run [service] [command]
: Run a one-off command against a service.- Unlike
exec
,run
starts a new container for the command, which is useful for tasks like database migrations.
docker-compose run web npm test # Run tests in a new 'web' container
- Unlike
-
docker-compose top
: Display the running processes of services.- Similar to
ps
, but shows the actual processes running inside your containers.
docker-compose top
- Similar to
Pro-Tips for Docker Compose Beginners 💡
- Always use
-d
for background processes: When deploying or just running your app for development in the background,docker-compose up -d
is your friend. - Rebuild often if needed: If you change your
Dockerfile
or add/remove files in your build context, remember todocker-compose up --build
ordocker-compose build
beforeup
. - Clean slate: If things go wrong and you want to start fresh,
docker-compose down --volumes
will give you a pristine environment (but remember it deletes data!). - Specify a Compose file: If your
docker-compose.yml
file has a different name or is in another directory, use the-f
flag:docker-compose -f /path/to/my-app/another-compose.yml up
. - Environment Variables: Use
.env
files or system environment variables for sensitive data like passwords, rather than hardcoding them indocker-compose.yml
. Compose automatically picks up.env
files in the same directory.
Conclusion 🎉
You’ve now got a powerful arsenal of Docker Compose commands at your fingertips! Understanding these commands will significantly boost your productivity and make managing multi-container applications a breeze.
The best way to learn is by doing. So, grab a docker-compose.yml
file (even the simple example above!) and start experimenting. Practice each command, observe its output, and you’ll become a Docker Compose wizard in no time. 🧙♂️
Happy Composing! 🐳✨