Starting a Container with a Volume
On Using -v Option
- we may start a container with a bind mount using the -v option:
$ docker run -v $(pwd):/var/opt/project bash:latest \
bash -c "ls /var/opt/project"
- This shows nothing from the mount position. However, if we write to the volume within a single execution of the container:
$ docker run -v data-volume:/var/opt/project bash:latest \
bash -c "echo Baeldung > /var/opt/project/Baeldung.txt"
Using The –mount Option
- To indicate the volume we want to mount, we might find it easier to use the more obvious –mount option:
$ docker run --mount \
'type=volume,src=data-volume,\
dst=/var/opt/project,volume-driver=local,\
readonly' \
bash -c "ls /var/opt/project"
On Using Shared Volumes
Assume that we used the data-volume mount in a container to run our echo script. Afterwards, we could make a list of every container we’ve used:
$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5774502f857 bash "docker-entrypoint.s…" 8 minutes ago Exited (0) 8 minutes ago exciting_payne
What Is Docker Volume?
Docker containers enable apps to execute in an isolated environment. All modifications made inside the container are lost by default when it ends. Docker volumes and bind mounts can be useful for storing data in between runs. One way to store data outside of containers is with volumes. All volumes are kept in a specific directory on your host, typically /var/lib/docker/volumes for Linux systems, and are controlled by Docker.