In this tutorial, we will learn how to use the -v option in the docker run command, which allows you to mount volumes when running a container.
Requirements
In this tutorial, we will be using the official Redis Docker image for demonstration purposes. This will teach you how to work with volumes in Docker.
Hence, you will need to ensure that you have the Docker engine installed on your host machine. We recommend using Docker version 23 and above.
Docker Run Container with Named Volume
The first step is to learn how to run a container with a named volume. To do this, we need to create a named volume and then run the container that stores in that volume.
To create a Docker volume, we can run the command as shown:
Once we have created the volume, we can run the Redis container and bind it to the volume as shown in the command below:
In the command above, we use the -d option to run the command in the background. We also specify the name of the container using the –name parameter.
Finally, we use the -v redis_data:/data to create a volume mount that links the /data directory inside the container to the named volume redis_data that we created in the previous step.
Using a Host Directory
In some cases, we can choose to use a host directory to store the data of a container. For example, start by creating the directory on the host system:
Next, we can run the container with a volume mount to the host directory, as shown in the command below:
In this case, we created a directory ~/redis_data on the host system and mounted it to the /data directory inside the Redis container.
Remove Named Volume
To remove an existing named volume in Docker, we can use the docker rm command as shown:
Ensure that no containers are using the specified named volume.
Conclusion
In this tutorial, we covered the fundamentals of working with container volumes by using the -v option in the docker run command.