如果您只删除了包含代码的目录,则该卷可能仍然存在。
使用docker-compose 时,您的docker-compose.yml 的父目录的名称会附加到卷名之前。
因此,如果要重用旧卷,则必须确保目录结构不会改变。
例如,使用以下docker-compose.yml:
version: "3"
services:
db:
image: postgres
volumes:
- postgres_data:/var/lib/postresql/data
volumes:
postgres_data:
在一个名为postgres2342 的目录中导致:
~/workspace/teststuff/postgres2342$ docker-compose up
Creating network "postgres2342_default" with the default driver
Creating volume "postgres2342_postgres_data" with default driver
Pulling db (postgres:)...
latest: Pulling from library/postgres
8ec398bc0356: Pull complete
65a7b8e7c8f7: Pull complete
b7a5676ed96c: Pull complete
3e0ac8617d40: Pull complete
633091ee8d02: Pull complete
b01fa9e356ea: Pull complete
4cd472257298: Pull complete
1716325d7dcd: Pull complete
9b625d69c7c8: Pull complete
74d8b4d9818c: Pull complete
c36f5edbeb97: Pull complete
9b38bb0fb36e: Pull complete
6b5ee1c74b9a: Pull complete
5fcc518252b4: Pull complete
Digest: sha256:52579625addc98a371a644c0399f37e0908b6c28d3b68a0e418394adbe0eb699
Status: Downloaded newer image for postgres:latest
Creating postgres2342_db_1 ... done
Attaching to postgres2342_db_1
注意开头的Creating volume "postgres2342_postgres_data" with default driver 和最后一行的Attaching to postgres2342_db_1。它对应于创建卷的名称。
如果我将撰写文件复制到另一个名为 another_postgres 的目录中并生成服务,则会导致:
~/workspace/teststuff/postgres2342$ cd ..
~/workspace/teststuff$ mkdir another_postgres
~/workspace/teststuff$ cp postgres2342/docker-compose.yml another_postgres/
~/workspace/teststuff$ cd another_postgres/
~/workspace/teststuff/another_postgres$ docker-compose up -d
Creating network "another_postgres_default" with the default driver
Creating volume "another_postgres_postgres_data" with default driver
Creating another_postgres_db_1 ... done
如您所见,卷的名称已更改。
使用docker volume ls,您可以显示系统上的所有 docker 卷。因此,对包含子字符串 postgres 的所有卷进行 greping 我得到:
apoehlmann:~/workspace/teststuff/another_postgres$ docker volume ls | grep postgres
local another_postgres_postgres_data
local postgres2342_postgres_data
但是,如果我删除目录并重新创建它而不更改其名称,一切都会正常:
~/workspace/teststuff/another_postgres$ cd ..
~/workspace/teststuff$ rm -r postgres2342/
~/workspace/teststuff$ mkdir postgres2342
~/workspace/teststuff$ cp another_postgres/docker-compose.yml postgres2342/
~/workspace/teststuff$ cd postgres2342/
~/workspace/teststuff/postgres2342$ docker-compose up
Starting postgres2342_db_1 ... done
Attaching to postgres2342_db_1
它将 postgres 服务附加到现有卷而不创建新卷。