Docker Compose explained for beginners

Image credit: Stephen Grider

What is Docker Compose?

Docker Compose is a tool for defining and running multi-container Docker applications. It uses a YAML file to configure your application’s services, networks, and volumes, enabling you to create and start all the services from your configuration with a single command.

Benefits of Using Docker Compose

  • Simplicity: Instead of typing long docker run commands with many arguments, you can declare your stack in a docker-compose.yml file and start everything with docker-compose up.
  • Consistency: The YAML configuration file ensures that the environment is consistent, no matter where you deploy it.
  • Networking: Containers spun up by Docker Compose can communicate with each other on the same network, making it easy to establish connections between services, such as linking a web application to a database server.
  • Volume Management: Just like with Docker volumes, Docker Compose allows you to mount volumes, making code or data persistence much more straightforward.

A Basic docker-compose.yml Example

Here’s a simplified example of what a docker-compose.yml file might look like for a web application:

version: '3'
services:
web:
build: .
ports:
- "5000:5000"
depends_on:
- db
db:
image: postgres
volumes:
- "db-data:/var/lib/postgresql/data"
volumes:
db-data:

In this example, we define two services: web and db. The web service builds from the current directory and maps port 5000 on the host to port 5000 in the container. It also declares a dependency on the db service, which uses the official postgres image and a named volume for data persistence.

Starting Services with Docker Compose

To start your services, you would typically run:

docker-compose up

If you need to build or rebuild the Docker images, you can include the --build flag:

docker-compose up --build

When you’re ready to stop and remove all the containers, networks, and volumes defined by your docker-compose.yml file, simply execute:

docker-compose down

This command stops all the running services associated with the docker-compose file and removes the containers, default network, and all images used by the containers. If you want to preserve the images, you can use the --rmi flag to control this behavior.

Conclusion

By defining your application stack in a docker-compose.yml file, you can eliminate manual Docker command repetition, improve productivity, and ensure that your development, testing, and production environments are aligned. Docker Compose not only saves time but also reduces the potential for errors, making your deployments more reliable and efficient.

,