Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Docker data volume


May 22, 2021 Docker From entry to practice



A data volume is a special directory for one or more containers that bypasses UFS and provides many useful features:

  • Data volumes can be shared and reused between containers
  • Changes to the data volume will take effect immediately
  • Updates to the data volume do not affect the mirror
  • The volume will remain present until no container is used

The use of data volumes is similar to mounting a directory or file under Linux.

Create a data volume

When docker run command, use -v tag to create a data volume and mount it into the container. You can mount multiple data volumes multiple times in a run.

Let's create a web container and load a data volume into the /webapp

$ sudo docker run -d -P --name web -v /webapp training/webapp python app.py

Note: YOU can also use VOLUME in Dockerfile VOLUME add one or more new volumes to any container created by the image.

Mount a host directory as a data volume

Using -v tag, you can also specify to mount a directory of a local host to the container.

$ sudo docker run -d -P --name web -v /src/webapp:/opt/webapp training/webapp python app.py

The above command loads the /src/webapp directory into the /opt/webapp directory. T his feature is convenient for testing, such as allowing users to place programs in the local directory to see if the container is working properly. The path to the local directory must be absolute, and if the directory does not exist Docker will automatically create it for you.

Note: This usage is not supported in Dockerfile because Dockerfile is for porting and sharing purposes. However, the path formats vary from operating system to operating system, so they are not currently supported.

The default permission for Docker to mount a data volume is read and write, and users can :ro as read-only.

$ sudo docker run -d -P --name web -v /src/webapp:/opt/webapp:ro
training/webapp python app.py

After the :ro it is mounted as read-only.

Mount a local host file as a data volume

-v tag can also mount a single file from the host to the container

$ sudo docker run --rm -it -v ~/.bash_history:/.bash_history ubuntu /bin/bash

This allows you to record the commands you have entered in the container.

Note: If you mount a file directly, many file editing tools, including vi sed --in-place may cause changes to the file inode, starting with Docker 1.1 .0, which can result in an error message. vi So the easiest way is to mount the parent directory of the file directly.