Data management with volumes

Estimated reading time:
5 minutes

In the previous step, we set up Redis but didn’t provide it a way to store the
data it’s caching. This means that if you redeployed the redis service, or if
the container crashed, the data would be lost. To save the data so it persists
beyond the life of a container, or share data from one container to another,
you need to define a volume.

Data persistence

To persist, data in Docker Cloud must be stored in a volume. The volume
can be defined on the image (for example in the Dockerfile), or specified when
you create a new service in the Docker Cloud web UI. Learn more about volumes in
Docker Cloud here.

Test for lack of persistence

If you redeploy the Redis service you created earlier, the counter resets.

Let’s try that. First, redeploy the redis service to reset the counter.

$ docker-cloud service redeploy redis --not-reuse-volumes

Check the container status using the container ps command, and wait until the new container is running again. In the example below you can see the original container in the “Terminated” state, and the new container that is “Starting”.

Enabling persistence

The specific Redis image (redis) in this tutorial supports data persistence.
This is not a common requirement for a Redis cache and it’s not enabled by
default in most images. However to activate this in our image, you only need
to set two environment variables.

Run the following command to create and set these two environment variables.

This command defines two new environment variables in the redis service and
then redeploys the service so they take effect. You can learn more about our
open source redis image here.

With these settings, Redis can create and store its data in a volume. The volume is in /data.

Visit the web endpoint a few more times to make sure that the cache is working
as expected. Then redeploy the Redis service to see if the counter resets, or if
it persists even after the container is terminated and re-created.

You now have a backup copy of the Redis data on your local host machine!

What’s Next?

Congratulations! You’ve completed the tutorials! You can now push an image to
Docker Cloud, deploy an app to your Cloud nodes, set environment variables,
scale the service, view logs, set up a load balancer and a data back end, and
set up a volume to save the data.