[Docker] Create a Volume

We can create volumn to keep the data, even we stop the container and restart again, the data won't get lost.

To create a link between the folder /my-files on your host machine and the htdocs folder in the container. This also runs the container in the background.

docker run -d -p 80:80 -v /my-files:/usr/local/apache2/htdocs web-server:1.1

 

After runnning the container, Let’s see what this looks like from inside the container.

Attache a shell to the container:

docker container exec -it elegant_noether /bin/bash

cd to folder:

cd /usr/local/apache2/htdocs

Now we can use 'ls -la' to see what is inside the folder.


Examples: 

// Create a Volume named "webdata"
docker volume create --name webdata

// Run a container points to "webdata" we just created
docker run -d --name web1 -v webdata:/usr/share/nginx/html -p 8000:/80 nginx

// Change index.html thought 
docker exec web1 bash -c 'echo "foo" > /usr/share/nginx/html/index.html'

// you can check the index.html 
curl localhost:8000

// Now let's remove the container
docker stop web1
docker rm web1

// Verify there is no running container
docker ps -a

// Create a new container with the same name as before
docker run -d --name web1 -v webdata:/usr/share/nginx/html/index.html -p 8000:80 nginx

// Chceck the data again
curl localhost:8000   // And we can see that it prints out "foo"

// We can export the same file to other container
docker run -d --name web2 -v webdata:/usr/share/nginx/html/index.html -p 8001:80 nginx

// Check the index.html file on web2
curl localhost:8001 // And we can see it prints out "foo" too

// Change the volume on one of the container
docker exec web1 bash -c 'echo "bar" > /usr/sgare/nginx/html/index.html'

// And we can see both container's data changed
curl localhost:8000
curl lcoalhost:8001

// To remove a volume, we need to stop all the containers 
docker stop web1 web2 && docker rm web1 web2
docker volume rm webdata

// Verify the volume was removed
docker volume ls

If you want to chck whether there is a volume inside a container:

docker inspect -f '{{.Mounts}}' web1

Inspect volume itself:

docker volume inspect webdata
原文地址:https://www.cnblogs.com/Answer1215/p/6745215.html