如何訪問Docker容器外部的文件

如果容器是隔離的,它們如何與主機通信,也許是為了存儲數據?因為當我們從圖像創建容器時,刪除容器後生成的所有數據都會丟失。

因此,我們需要一種永久存儲的方法。

我們可以使用綁定坐騎卷數

兩者之間沒有太大區別,除了Bind Mounts可以指向主機上的任何文件夾,並且不直接由Docker管理。

讓我們從他們開始。一個經典的例子是日誌。假設您的應用在容器中的以下位置創建了一個日誌文件:/usr/src/app/logs。您可以使用-v(與...一樣--volume)當您使用以下命令運行容器時docker run, 像這樣:-v ~/logs:/usr/src/app/logs

這會將該文件夾映射到用戶主目錄中的logs子文件夾。

節點:-m或者--mount標誌的工作方式非常相似

這是與examplenode我們之前創建的圖像:

docker run -d -p 80:3000 -v ~/logs:/usr/src/app/logs --name node-app examplenode

因此,現在我們可以運行Node應用程序,所有日誌都將存儲在主機中,而不是Docker容器中。

請注意examplenode應用程序不會生成任何登錄信息/usr/src/app/logs,這只是一個示例,您需要先設置該日誌記錄。

運行時將列出有關該卷的詳細信息docker inspect在容器名稱的“掛載”下:

"Mounts": [
    {
        "Type": "bind",
        "Source": "/Users/flavio/logs",
        "Destination": "/usr/src/app/logs",
        "Mode": "",
        "RW": true,
        "Propagation": "rprivate"
    }
],

Can you see "Type": "bind"? That means that we have created a bind mount.

Now, let’s talk about Volumes.

The difference between Bind Mounts and Volumes is that by creating volumes, Docker will store the data in a folder it manages, which means it will take care of file permissions and ownership, and it will give you the tools to manage those volumes. While bind mounts are based on filesystem paths, and Docker can’t provide the tooling around them.

For example, Docker lets you remove all unused volumes by running docker volume prune or docker system prune --volumes.

To create a volume, we first need to run docker volume create:

docker volume create logs

Now you can use docker volume ls and docker volume inspect to get more data about the system volumes:

Now run docker run with the option -v logs:/usr/src/app/logs (tell the volume name instead of a folder)

docker run -d -p 80:3000 -v logs:/usr/src/app/logs --name node-app examplenode

Now running docker inspect on the image will show the mounted volume:

"Mounts": [
    {
        "Type": "volume",
        "Name": "logs",
        "Source": "/var/lib/docker/volumes/logs/_data",
        "Destination": "/usr/src/app/logs",
        "Driver": "local",
        "Mode": "z",
        "RW": true,
        "Propagation": ""
    }
],

See? Now the logs will be stored in the /var/lib/docker/volumes/logs/_data folder.

Volumes will be essential when it will be time to deploy a container on a cloud service, for example.

You can remove a volume running docker volume rm <name>.


More docker tutorials: