A Brief introduction to Docker data persistence

  • 2020-10-31 22:03:11
  • OfStack

There are two main ways to persist data in a container:

Data Volume (Data Volumes) Data volume container (Data Volumes Dontainers)

Data volume

A data volume is a special directory that can be used by one or more containers to bypass UFS (Unix File System).

Data volumes can be Shared and reused between containers Changes to the data volume take effect immediately Updates to data volumes do not affect mirroring The data volume will exist 1 by default, even if the container is deleted A container can mount multiple data volumes

Note: The use of data volumes is similar to mount for directories or files under Linux.

Creating a data volume

Example:


docker run --name nginx-data -v /mydir nginx

To see the details of the container construction, execute the following command:


docker inspect  The container ID

It can be known from the test that:

Docker automatically generates 1 directory as a mounted directory. Even if the container is deleted, the directory in the host machine is not deleted.

Delete data volume

Data volumes are designed to persist data, so deleting the container does not remove the volume. If you want to delete the data volume while deleting the container, use the following command:


docker rm -v  The container ID

This removes both the container and the data volume.

Mount the host directory as a data volume


docker run --name nginx-data2 -v /host-dir:/container-dir nginx

This will either load the host/ES41en-ES42en path into the container/ES43en-ES44en.

It should be noted that:

The host path should be as absolute as possible -- what if relative paths are used?

The test gives the answer

If the host path does not exist, Docker is created automatically

TIPS

Dockerfile does not support this format for the time being.

Mount the host file as a data volume


docker run --name nginx-data3 -v / The file path :/container The path  nginx

Specify the permissions

By default, the permissions mounted are read and write permissions. Read - only permissions can also be specified using the :ro parameter.

Example:


docker run --name nginx-data4 -v /host-dir:/container-dir:ro nginx

In this way, only the files in/ES72en-ES73en can be read in the container and not modified.

Data volume container

If you have data that needs to be Shared between multiple containers, consider using a data volume container.

Create a data volume container:


docker run --name nginx-volume -v /data nginx

Use -ES83en-ES84en in other containers to mount data volumes in nginx-ES86en containers.


docker run --name v1 --volumes-from nginx-volume nginx
docker run --name v2 --volumes-from nginx-volume nginx

Like this:

v1 and v2 can share files in the nginx-ES95en container.

Even if ES99en-ES100en is stopped, it will not have any effect.


Related articles: