Nov 01, 2018

11 min read

Docker Volumes: How To Protect Your App’s Data

Written by

Vippy The VPS
Docker containers are designed to be short-lived. If a new version of an application is released, we don’t login inside our container and run apt upgrade to install the newer version—we simply replace it with a different container running the more recent version of the application. Docker volumes essential to making short-lived containers but persistent data. Docker is designed to package an application and its dependencies in a new way: the container. Before containers were the norm on many servers, people often had issues with upgrades. For example, a developer upgraded their site from PHP 5 to PHP 7 but failed to update all the required PHP modules, and then things fell apart. Developers also struggled with having different environments on their local machine and the deployment server due to slightly different packages. Docker is supposed to bridge these differences. For a PHP 7 environment, you start with a clean-slate environment where you develop and test your application. You then package that into a Docker image, which spawns the same container regardless of where you run it. Dropping into a container and upgrading software from inside is an anti-pattern: You no longer have a clean slate, and you defeat the very purpose of using Docker. An application is not all its environment and code, however. There’s valuable data, media files, a user database, posts, and more, all of which needs to be kept around across upgrades. If you remove an old container, you also lose all its data unless you decouple the data from the container. Unless you use Docker volumes.

What are Docker volumes?

Docker volumes persistently store data, which can be made available to containers. For example, if you create a volume named my-vol it will create a directory at /var/lib/docker/volumes/my-volume on your host system. You don’t need to know the exact location on the host, as Docker manages the volume for you and allows you to mount it on any new container. The container can write data to this volume, which persist even after you remove the container. Let’s create a couple of containers, one without a volume and another with one, to see the difference.

Ephemeral storage without volumes

To simulate user data, we will log in to the container, create a directory /app-v1/content/, and in it write a file data.txt with the message “Hello, World!” in it.
$ docker run -dit --name container1 ubuntu:16.04
$ docker
Continue reading this article
by subscribing to our newsletter.
Subscribe now

Leave a Reply