Docker volumes are used to persist data from within a Docker container. There are a few different types of Docker volumes: host, anonymous, and, named. Knowing what the difference is and when to use each type can be difficult, but hopefully, I can ease that pain here.
Why Docker Volumes?
Docker volumes are the preferred way to save data over restarts of a Docker container. When compared to bind mounts, here are some of advantages of volumes:
- Volumes are easier to back up and migrate.
- Managing volumes can done from the Docker CLI or Docker API.
- They work on Linux and Windows.
- Volumes are safer to share among containers.
- Volume drivers allow volumes to be stored on remote hosts or cloud providers or to be encrypted.
- New volumes can be pre-populated by the container.
- Volumes do not increase the size of the container.
When to Use Each Volume
There are a few different types of volumes, each with its own purpose and benefits.
A host volume can be accessed from within a Docker container and is stored on the host, as per the name. To create a host volume, run:
docker run -v /path/on/host:/path/in/container
I suggest using a host volume when you need to know where to refer to the data. It’s also the easiest type of volume to use, so it’s ideal for simple projects.
The location of anonymous volumes is managed by Docker. Note that it can be difficult to refer to the same volume when it is anonymous. To create an anonymous volume, run:
docker run -v /path/in/container ...
Anonymous volumes provide flexibility, but they aren’t used as often now that named volumes have been introduced.
Named volumes and anonymous volumes are similar in that Docker manages where they are located. However, as you might guess, named volumes can be referred to by specific names. To create a named volume, run:
docker volume create somevolumename docker run -v name:/path/in/container ...
Like anonymous volumes, named volumes provide flexibility, but they are also explicit. This makes them easier to manage.
You can also specify Docker volumes in your docker-compose.yaml file using the same syntax as the examples above. Here’s an example of a named volume I used in a WordPress Docker container.
volumes: - db_data:/var/lib/mysql
Volumes are helpful for saving data across restarts of your Docker containers. If you need to use a volume, consider the difference between the various kinds before starting development. This will make it easier to save data from the start and specify your volume in your Dockerfile.