Data generated and used by Docker containers does not persist after restarts. We use Docker volumes to manage data to solve this issue. We use it to persist data in a container or share data between containers.
Volumes are the preferred mechanism for persisting data generated and user by Docker containers. Volumes are easier to back up or migrate.
Volumes are often a better choice than persisting data in a container’s writable layer, because a volume does not increase the size of the containers using it. The volume’s contents exist outside the lifecycle of a given container.
We have 3 volume types:
Anonymous volumes
Helpful to persist data temporarily. If we restart our container data is still visible. It doesn’t persist when we remove the container. Not accessible by other containers. They’re created inside /var/lib/docker/volume
.
Example file:
version: '3.8'
services:
db:
image: mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: test_db
ports:
- "3306:3306"
volumes:
- /var/lib/mysql
Named Volumes
Named volumes can persist data after we restart or even after we delete the container. They’re accessible by other containers. They’re created inside /var/lib/docker/volume
.
This is the one we’re going to use.
Example file:
version: '3.8'
services:
db:
image: mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: test_db
ports:
- "3306:3306"
volumes:
- db_data:/var/lib/mysql
volumes:
db_data:
The first field is a unique name of the volume on a host machine. The second field is the path inside the container.
Bind Mounts
They’re the same as named volumes except bind mounts can be any host directory. Named volumes can be found under a specific host directory.
Named volumes are preferred over Bind Mounts. Bind mounts are dependent on directory structure of the host machine. Volumes are completely managed by docker.
Example file:
version: '3.8'
services:
db:
image: mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: test_db
ports:
- "3306:3306"
volumes:
- $PWD/data:/var/lib/mysql
This mounts a host folder. First path is the path in the machine. Second path is inside the container.
How to export/import docker named volumes for a container
A running container can be exported into a tar archive, which can be copied to a different machine and then be imported back.
To export where the container is running:
docker export --output "A.tar" <container-A>
To import it back into the new machine:
docker import A.tar <container-image-A>
Reference(s)
https://docs.docker.com/storage/volumes/
https://towardsdatascience.com/the-complete-guide-to-docker-volumes-1a06051d2cce
https://stackoverflow.com/questions/47646419/how-to-import-export-docker-compose