我意识到这是一个古老且已解决的线程,其中 OP 指向容器中的目录而不是它们已安装的卷,但想清除我看到的一些错误信息。
docker-compose down
不删除卷,docker-compose down -v
如果您还想删除卷,则需要运行。这是直接来自 docker-compose 的帮助文本(注意“默认”列表):
$ docker-compose down --help
Stops containers and removes containers, networks, volumes, and images
created by `up`.
By default, the only things removed are:
- Containers for services defined in the Compose file
- Networks defined in the `networks` section of the Compose file
- The default network, if one is used
Networks and volumes defined as `external` are never removed.
Usage: down [options]
Options:
...
-v, --volumes Remove named volumes declared in the `volumes` section
of the Compose file and anonymous volumes
attached to containers.
...
$ docker-compose --version
docker-compose version 1.12.0, build b31ff33
这是一个带有要测试的命名卷和一个虚拟命令的示例 yml:
$ cat docker-compose.vol-named.yml
version: '2'
volumes:
data:
services:
test:
image: busybox
command: tail -f /dev/null
volumes:
- data:/data
$ docker-compose -f docker-compose.vol-named.yml up -d
Creating volume "test_data" with default driver
Creating test_test_1
启动容器后,卷初始化为空,因为该位置的映像为空。我在那个位置创建了一个快速的hello world:
$ docker exec -it test_test_1 /bin/sh
/ # ls -al /data
total 8
drwxr-xr-x 2 root root 4096 May 23 01:24 .
drwxr-xr-x 1 root root 4096 May 23 01:24 ..
/ # echo "hello volume" >/data/hello.txt
/ # ls -al /data
total 12
drwxr-xr-x 2 root root 4096 May 23 01:24 .
drwxr-xr-x 1 root root 4096 May 23 01:24 ..
-rw-r--r-- 1 root root 13 May 23 01:24 hello.txt
/ # cat /data/hello.txt
hello volume
/ # exit
该卷在 docker 外部可见,并且在 a 之后仍然存在docker-compose down
:
$ docker volume ls | grep test_
local test_data
$ docker-compose -f docker-compose.vol-named.yml down
Stopping test_test_1 ... done
Removing test_test_1 ... done
Removing network test_default
$ docker volume ls | grep test_
local test_data
重新创建容器使用旧卷,其中文件仍然可见:
$ docker-compose -f docker-compose.vol-named.yml up -d
Creating network "test_default" with the default driver
Creating test_test_1
$ docker exec -it test_test_1 /bin/sh
/ # cat /data/hello.txt
hello volume
/ # exit
并运行docker-compose down -v
finally 删除容器和卷:
$ docker-compose -f docker-compose.vol-named.yml down -v
Stopping test_test_1 ... done
Removing test_test_1 ... done
Removing network test_default
Removing volume test_data
$ docker volume ls | grep test_
$
如果您发现您的数据仅在使用停止/启动而不是向下/向上时才被持久化,那么您的数据将存储在容器(或可能是匿名卷)而不是您的命名卷中,并且容器不是执着的。确保容器内数据的位置正确以避免这种情况。
要调试数据存储在容器中的位置,我建议docker diff
在容器上使用。这将显示在该容器内创建、修改或删除的所有文件,这些文件在容器被删除时将丢失。例如:
$ docker run --name test-diff busybox \
/bin/sh -c "echo hello docker >/etc/hello.conf"
$ docker diff test-diff
C /etc
A /etc/hello.conf