Getting started with Docker Compose

Deepika Juneja
2 min readOct 20, 2022

--

Source: https://www.docker.com/

Let’s do a quick recap of docker run command first! In order to run an instance of a docker image, we use the command,

docker run -d --name=some-name -p 80:80 some-image

Now, if we need to run multiple instances of the image, we will need to execute the above command again and again. Even the management of multiple containers will become quite cumbersome. Is there any better way to do this?

The answer to this is Docker Compose. Docker Compose helps us to define and run multi-container applications efficiently. This is achieved by specifying all the configurations in a YAML file (named docker-compose.yml). Then, with the help of a single command, we can run all the services at once!

Structure of docker compose file

version: "3.9"  # optional since v1.27.0
services:
...
volumes:
...
networks:
...
  1. version: Indicates which version of docker compose is being used.
  2. services: Defines all the containers that will be created in this application, along with their configurations.
  3. volumes: Specifies the volumes that can be used across multiple services in the application.
  4. networks: Specifies the network which will be used by the application.

Services

services:
frontend:
image: my-webapp
ports:
- "5000:80"
networks:
- front-end
- back-end

backend:
image: my-webapp-database
volumes:
- db-data:/etc/data
networks:
- back-end
  1. image: Specifies the image whose instance (container) is to be created.
  2. ports: Exposes container ports to the host machine.
HOST:CONTAINER

3. networks: Specifies networks that the service containers are attached to.

4. volumes: Specifies volumes that are accessible to service containers.

Networks

networks:
front-end:
back-end:

Volumes

volumes:
db-data:

Commonly used docker compose commands

  1. To build/re-build services:
docker compose build

2. To create and start services:

docker compose up

3. To start existing containers:

docker compose start <service-name>

4. To stop containers:

docker compose stop <service-name>

5. To remove stopped containers:

docker compose rm <service-name>

6. To stop and remove containers:

docker compose down

7. To list all images:

docker compose images

8. To list all running containers:

docker compose ps

--

--

Deepika Juneja

Application Developer at ThoughtWorks | Software Engineer | Tech Enthusiast | Potterhead