Sometimes we need persistent data during the time, even when a container is deleted, in these cases we use persistent volumes with docker.
By default all files created inside a container are stored on a writable container layer. This means that:
- The data doesn’t persist when that container no longer exists, and it can be difficult to get the data out of the container if another process needs it.
- A container’s writable layer is tightly coupled to the host machine where the container is running. You can’t easily move the data somewhere else.
- Writing into a container’s writable layer requires a storage driver to manage the filesystem. The storage driver provides a union filesystem, using the Linux kernel. This extra abstraction reduces performance as compared to using data volumes, which write directly to the host filesystem.
Docker has two options for containers to store files in the host machine, so that the files are persisted even after the container stops: volumes, and bind mounts. If you’re running Docker on Linux you can also use a tmpfs mount. If you’re running Docker on Windows you can also use a named pipe.
In this entry we will use the persistent volumes with Docker, keep reading for understand how they work.
First of all we need a directory to store our yaml files and docker-compose installed, obviously we need a docker-engine in our system.
[[email protected] ~]# mkdir -p /srv/docker-files/mysql && touch /srv/docker-files/mysql/docker-compose.yml
Fill the file with the following code.
version: '2' services: mysql: container_name: mysql-server restart: always image: mysql/mysql-server environment: MYSQL_ROOT_PASSWORD: 'root' MYSQL_USER: 'user' MYSQL_PASS: 'user' volumes: - mysql-volume:/var/lib/mysql volumes: mysql-volume:
Use the docker compose command inside the folder:
[[email protected] ~]# docker-compose up -d
Creating volume “mysql_persistent-volume” with default driver
If we list our volumes some data will be prompted:
[[email protected] ~]# docker volume ls
DRIVER VOLUME NAME
[[email protected] ~]# docker volume inspect mysql_persistent-volume
Now connect to the mysql through the command exec and create a database.
[[email protected] ~]# docker exec -it 05bc7019e294 /bin/bash
bash-4.2# mysql -p
[[email protected] ~]# mysql> create database codinginfrastructure;
Query OK, 1 row affected (0.02 sec)
Leave from the container and remove it, first you must stop the container.
[[email protected] ~]# docker stop 05bc7019e294
docker rm 05bc7019e294
Now the docker ps -a command will not return us any container. Now try to build again your container with docker-compose up -d and check again your database. You will see the database that we created before. Even after to remove the container. Thats fantastic!
You can read more information about the volumes at docker page.