1. Introduction
Using Dockerfile
As mentioned earlier, changes made to the Docker container are not actively saved unless you commit, or you rerun the image to create a new container, the contents of the previous container will be gone, because the container is just a process.
Therefore, the container runtime should try to keep the container storage layer write free.
However, sometimes we need to store persistent data, such as a database, and your data is all in a container, which is not possible, because it’s gone as soon as you exit.
This is where the data volume is needed.
Data volumes allow you to mount data from a host to a container so that different containers can share data without losing it when the container exits.
This data volume will be used frequently.
2. Use
Let’s take a look at the functions of data volumes.
$ docker run -d -v ~/mynginx:/a -p 80:80 --name webserver nginx
Copy the code
Here the command will mount the host directory ~/mynginx to the container directory /a.
You can experiment by changing the content at both ends, such as creating a new file, to see if everything changes.
We can also create a data volume container, which is also a normal container that provides and shares data with other containers.
For example, we create a data volume container:
$ sudo docker run -d -v /dbdata --name dbdata training/postgres echo Data-only container for postgres
Copy the code
To use the data volume container, run the –volumes-from parameter.
$ sudo docker run -d --volumes-from dbdata --name db1 training/postgres
$ sudo docker run -d --volumes-from dbdata --name db2 training/postgres
Copy the code
The end.
Docker Compose installation for Docker Compose