我意识到这是一篇旧的和已解决的帖子,原帖作者指向容器中的目录而不是他们挂载的卷,但我想澄清一些我看到的错误信息。
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 外部可以看到该卷,并且在执行 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
/
hello volume
/
最后运行docker-compose down -v
命令将会移除容器和卷:
$ 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
down
命令,但默认情况下它不会删除任何卷。 - dnephin