Skip to main content

How to declare a volume in docker-compose.yml?

A volume is declared in docker-compose.yml in two places:

1. Inside the service (where the volume is mounted)

yaml
services: app: image: nginx volumes: - mydata:/usr/share/nginx/html

Here mydata is the volume that is connected to the path inside the container.

2. At the bottom of the file (where the volume is described)

yaml
volumes: mydata:

What happens

  • in the services section - we mount the volume into the container
  • in the volumes section - we declare that the volume exists

Summary

A complete minimal example:

yaml
services: app: image: nginx volumes: - mydata:/usr/share/nginx/html volumes: mydata:

After docker compose up, Docker creates mydata itself and mounts it into the container.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.