In this scenario, you'll learn how to use Docker Volumes to persistent data within Containers. Docker Volumes allow directories to be shared between containers and container versions.
Docker Volumes allows you to upgrade containers, restart machines and share data without data loss. This is essential when updating database or application versions.
Persisting Data Using Volumes
Step 1 - Data Volumes
Docker Volumes are created and assigned when containers are started. Data Volumes allow you to map a host directory to a container for sharing data.
This mapping is bi-directional. It allows data stored on the host to be accessed from within the container. It also means data saved by the process inside the container is persisted on the host.
This example will use Redis as a way to persist data. Start a Redis container below, and create a data volume using the -v parameter. This specifies that any data saved inside the container to the /data directory should be persisted on the host in the directory /docker/redis-data.
docker run -v /docker/redis-data:/data \
--name r1 -d redis \
redis-server --appendonly yes
We can pipe data into the Redis instance using the following command.
cat data | docker exec -i r1 redis-cli --pipe
Redis will save this data to disk. On the host we can investigate the mapped direct which should contain the Redis data file.
This same directory can be mounted to a second container. One usage is to have a Docker Container performing backup operations on your data.
docker run -v /docker/redis-data:/backup ubuntu ls /backup