# docker volume

使用 volume 時，docker 會在你的本機上隨機新增一個本地資料夾（Local storage area），大部分會在/var/lib/docker/volumes/底下，然後讓**這個資料夾跟 container 裡面的某個資料夾互通**。

因為他們是互通的，所以當你 container 裡面那個資料夾有任何變更時，本地的資料夾也會跟著變，而且很重要的一點是：***container 被刪掉時那個資料夾資料仍被保留，***&#x6211;們就可以利用這個特性保留容器裡面的資料。

替容器裡面的/data目錄建立相通的永久volume

```
docker run -it -v /data --name=container1 busybox sh
exit

docker volume ls
DRIVER              VOLUME NAME
local               2b44e16bfe8a7417e6ef183e9b9824936a490bff0c4122568437a449f85d52a1
local               283861498c6d94b05dfed40237066e05e955f916ae94e6ac8c5a9070d8dcc058
docker start container1
docker inspect container1
```

![](/files/-LkRQTJodM9uo5knLiG4)

![](/files/-LkRPfg96zy5wCZHZnaC)

## 讓 Container 和 Container 之間的資料共享

啟動第二個 Container 指令如下

```
docker run -it --volumes-from container1 --name=container2 busybox sh
```

![](/files/-LkRRh1nuSwXcKH_zZiI)

```
root@kawsing:/# cd /var/lib/docker/volumes/2b44e16bfe8a7417e6ef183e9b9824936a490bff0c4122568437a449f85d52a1/_data/
root@kawsing:/var/lib/docker/volumes/2b44e16bfe8a7417e6ef183e9b9824936a490bff0c4122568437a449f85d52a1/_data# ls
helloworld2.txt  helloworld.txt
```

### 新增一個named volume <a href="#id-27f8" id="id-27f8"></a>

```
docker volume create --name data
docker volume ls
真實路徑位於/var/lib/docker/volumes/data/_data
```

![](/files/-LkRAgiMnui5m23Xtnqm)

![](/files/-LkRCeJzTC7AIEcKZiHz)

![](/files/-LkRD9UX7szX7JdR5jXI)

![](/files/-LkRCoJT-UaBJrazwRne)

### 再次啟動容器

docker run --name testvolume -v data:/tmp **-itd** busybox sh

![](/files/-LkRDxNYYfxVQ3R-DvvR)

![](/files/-LkRFve_5EQVEq3lF8Yz)

```
docker volume inspect data
[
    {
        "CreatedAt": "2019-07-23T00:22:18Z",
        "Driver": "local",
        "Labels": {},
        "Mountpoint": "/var/lib/docker/volumes/data/_data",
        "Name": "data",
        "Options": {},
        "Scope": "local"
    }
]
```

## 新增一個 HOST volume

&#x20;docker volume create data 使用的 volume 稱作 **named volume**，而現在要介紹另外一種叫做 **host volume**，用來直&#x63A5;***指定某個資料夾***&#x8DDF;容器內的資料夾連通

```
docker run --name hostvolume -v /docker/busybox/tmp:/tmp -itd busybox sh
cd /docker/busybox/tmp
echo "Host volume create" > fromhostvolume.txt
```

![](/files/-LkRVbdTyewL6Ii2Qvtw)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kawsing.gitbook.io/opensystem/docker-cong-an-zhuang-dao-ying-yong-ru-men-pian/docker-volume.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
