How to mount a volume in a container?
A volume is mounted into a container using the -v (or --mount) flag when starting the container. The formula is simple:
javascript
docker run -v <volume_name>:<path_inside_container> image_nameExample
Let's create a volume and mount it into a container:
bash
docker volume create mydata
docker run -d -v mydata:/usr/share/data nginxmydata- the volume on the host/usr/share/data- the folder inside the containernginx- the image
Now everything the container writes to /usr/share/data will be stored in the volume and will not disappear when the container is recreated.
In docker-compose.yml
compose uses the same principle:
yaml
services:
app:
image: nginx
volumes:
- mydata:/usr/share/data
volumes:
mydata:In short: to mount a volume, specify -v volume_name:path_in_container, or do the same in docker-compose.yml.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.