How to use Docker Volumes In Docker
Manually Creating and Linking Volumes with Proper Naming And Labeling Conventions
- Make sure you use appropriate name and labelling practices when establishing Docker volumes.
docker volume create \
--label description="my_vol" \
--label version="1.0.1" \
my_vol
Using Volumes in Dockerfiles with Controlling Permissions For Volumes
- In order to preserve data security and integrity, make sure the appropriate permissions are specified for Docker volumes.
FROM baseimage
RUN mkdir /app/data
RUN chown -R 1000:1000 /app/data
RUN chmod 647 /app/data
VOLUME /app/data
Mounting Volumes as Read-Only
Mounting volumes as read-only in Docker allows for the protection of sensitive or critical data from unintended modifications. By setting the volume option to read-only, you ensure that any changes made within the container are not persisted to the underlying volume, preserving data integrity and security.
docker run -d \
-v /path/on/host:/path/in/container:ro \
--name my_container \
my_image
-v /path/on/host:/path/in/container:ro
mounts the directory/path/on/host
on the host machine to/path/in/container
in the container as read-only (ro
).--name my_container
assigns the namemy_container
to the Docker container.my_image
is the name of the Docker image used to create the container.
Tracking And Controlling Volume Consumption
- To maximise resource consumption, track and adjust Docker volume usage on a regular basis.
$ docker system df -v
Populating Volume Content
When mounting volumes to container paths with existing data, Docker ensures data integrity by copying the existing container data into the new volume. Consequently, neighboring mount points and other containers using the volume will also access the populated content, preventing inadvertent data loss.
Reusing Volumes When Containers Start
Instead of manually specifying each volume with the -v flag, you can use –volumes-from to inherit volumes from an existing container when starting a new container:
# Create the first container
$ docker run -d --name test -v my_vol:/data image:latest
# Create the second container
$ docker run -d --name backup --volumes-from test image:latest
This command automatically mounts all volumes from the “test” container into the “backup” container, simplifying the setup process. It’s handy for tasks like backing up data from one container to another.
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.