How to mount a volume in a Docker container?

Published on Aug. 22, 2023, 12:19 p.m.

To mount a volume in a Docker container, you can use the -v or --volume option in the docker run command. This option takes the path of the source directory or file on the host machine, and the path of the destination directory or file in the container.

For example, to mount the directory /home/user/data on the host machine to the directory /data in the container, you can run the following command:

docker run -v /home/user/data:/data <image>

Replace <image> with the name of the Docker image you want to run.

This will create a volume in the container that is linked to the directory /home/user/data on the host machine. Any data written to the /data directory inside the container will be persisted on the host machine, and any changes made to the /home/user/data directory on the host machine will be visible inside the container.

You can also use named volumes or anonymous volumes to mount a volume in a Docker container. To create a named volume, use the docker volume create command, and then use the --mount option to mount it in the container. For anonymous volumes, use the --mount option with the type=volume flag. For example:

# Create a named volume
docker volume create myvolume

# Mount the named volume in the container
docker run --mount source=myvolume,target=/data <image>

# Mount an anonymous volume in the container
docker run --mount type=volume,target=/data <image>

Replace <image> with the name of the Docker image you want to run.

Tags: