There are two main ways to persist data in containers:
- Data Volumes
- Data Volumes Dontainers
Data volume
A data volume is a special directory that can be used by one or more containers and can bypass UFS (Unix File System).
- Data volumes can be shared and reused among containers
- Modification of data volumes will take effect immediately
- Updates to data volumes will not affect the mirroring
- The data volume will always exist by default, even if the container is deleted
- One container can mount multiple data volumes
Note: The use of data volumes is similar to mounting directories or files under Linux.
Create a data volume
Example:
docker run --name nginx-data -v /mydir nginx
Run the following command to view the details of the container structure:
docker inspect containerID
From the test, we can see:
- Docker will automatically generate a directory as the mounted directory.
- Even if the container is deleted, the directory in the host will not be deleted.
Delete data volumes
Data volumes are designed to persist data, so deleting containers does not delete data volumes. If you want to delete the data volume while deleting the container, you can use the following command:
docker rm -v containerID
This allows you to delete the container while deleting the data volume.
Mount the host directory as a data volume
docker run --name nginx-data2 -v /host-dir:/container-dir nginx
This allows the host's /host-dir path to load the container's /container-dir path.
What should be noted is:
Try to set an absolute path to the host path - what happens if the relative path is used?
- Test to answer
If the host path does not exist, Docker will automatically create it
TIPS
Dockerfile does not support this form for the time being.
Mount the host file as a data volume
docker run --name nginx-data3 -v /File path:/containerpath nginx
Specify permissions
By default, the mount permission is read and write permission. You can also use the :ro parameter to specify read-only permissions.
Example:
docker run --name nginx-data4 -v /host-dir:/container-dir:ro nginx
In this way, the files in /container-dir can only be read in the container, but cannot be modified.
Data volume container
If there is data that needs to be shared among multiple containers, consider using a data volume container at this time.
Create a data volume container:
docker run --name nginx-volume -v /data nginx
Use -volumes-from in other containers to mount data volumes in nginx-volume containers.
docker run --name v1 --volumes-from nginx-volume nginx docker run --name v2 --volumes-from nginx-volume nginx
so:
The files in nginx-volume containers can be shared by v1 and v2.
Even if nginx-volume is stopped, there will be no effect.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.