Persisting Data with Docker Volumes

Persisting Data with Docker Volumes


2 min read

Intro: When running database containers like MySQL or MongoDB, we often want the data to persist even when the container is stopped or deleted. By default, containers use ephemeral storage that disappears when the container is removed. In this guide, we will use Docker volumes to attach persistent storage to a MySQL container

Step 1: Run a MySQL Container

First, we will run a MySQL container from the official image. The -d flag runs it in detached mode:

docker run -d --name mysql -e MYSQL_ROOT_PASSWORD=123456 mysql

Step 2: Create a Docker Volume

Next, create a volume to store the MySQL data:

docker volume create mysql-data

This creates a volume named mysql-data.

Step 3: Run MySQL with Persistent Storage

Now we can run MySQL again, this time mounting the volume on the data path:

docker run -d --name mysql -e MYSQL_ROOT_PASSWORD=123456 -v mysql-data:/var/lib/mysql mysql

The -v flag mounts the mysql-data volume to the container's /var/lib/mysql where data is stored.

Step 4: Test Data Persistence

Let's connect to MySQL container and create a test database and table:

docker exec -it mysql mysql -uroot -p123456

mysql> CREATE DATABASE appdata;
mysql> USE appdata; 
mysql> CREATE TABLE test (id INT, name VARCHAR(5));
mysql> INSERT INTO test VALUES (1, 'John');
mysql> exit

Now when we stop and remove the MySQL container, then run a new one mounting the same volume, the database and data persist:

docker stop mysql
docker rm mysql

docker run -d --name mysql -e MYSQL_ROOT_PASSWORD=123456 -v mysql-data:/var/lib/mysql mysql

docker exec -it mysql mysql -uroot -p123456

mysql> USE appdata;
mysql> SELECT * FROM test;
| id   | name  |
|    1 | John  |

The test data we inserted is still available in the new container's mounted volume!

Conclusion: With Docker volumes, we can provide persistent storage for containers like databases. Data can survive container restarts and upgrades. This avoids losing critical data stored in ephemeral container filesystems.

Did you find this article valuable?

Support Edvin Dsouza by becoming a sponsor. Any amount is appreciated!