Docker

Docker Run -v Example

Docker volumes are essential when you need to persist and share data between containers and the host system. They are particularly useful if your application needs to store data across reboots. For example, if you are using a database application, you might want to ensure that the data is not lost when the container is not stopped or removed.

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:

$ docker volume create redis_data

Once we have created the volume, we can run the Redis container and bind it to the volume as shown in the command below:

$ docker run -d --name redis-server -v redis_data:/data redis

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:

$ mkdir ~/redis_data

Next, we can run the container with a volume mount to the host directory, as shown in the command below:

$ docker run -d --name redis-server -v ~/redis_data:/data redis

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:

$ docker volume rm redis_data

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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list