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/htmlHere 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
servicessection - we mount the volume into the container - in the
volumessection - 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.