使用 docker 删除命名卷?

如果我有这样的文件:

version: "3"
services:
postgres:
image: postgres:9.4
volumes:
- db-data:/var/lib/db
volumes:
db-data:

然后执行 docker-compose updb-data创建一个命名卷。有没有办法通过 docker-compose移除这个卷?如果它是一个匿名卷,那么 docker-compose rm -v postgres就可以做到这一点。但就目前而言,我不知道如何在不返回到 docker命令的情况下删除 db-data卷。感觉这应该是可能的,从内部的 docker-compose CLI。我错过了什么吗?

61646 次浏览
docker-compose down -v

removes all volumes attached. See the docs

There's no way to target the removal of a specific named volume with the docker-compose cli. Instead this can be achieved using the docker cli. See the docs.

Use docker volume ls to find the name of specific volume.

Remove the volume using docker volume rm VOLUME_NAME. You will need to have stopped and removed containers using the volume.

An example approach:

# Stop and remove container's using the target volume
docker-compose stop NAME_OF_CONTAINER


# We need the force flag, "-f", as the container is still bound to the volume
docker-compose rm -f NAME_OF_CONTAINER


# Next find your volume name in the following list
docker volume ls


# Finally remove the volume
docker volume rm VOLUME_NAME

I had the same issue as you, excepting I wanted to discard the working state of my grafana container while leaving the other containers running, which are running detached (ie. sudo docker-compose up -d). Here's the procedure I've come up with:

sudo docker-compose ps
sudo docker-compose stop grafana
sudo docker-compose rm --force grafana
sudo docker volume rm metricsmonitoring_grafana_data
sudo docker-compose up --force-recreate -d grafana

I don't know (without playing further) how best to determine the name of the docker volume to remove.

This is on docker-compose version 1.18.0

Jan, 2022 Update:

This removes all the containers, networks, volumes and images defined in the docker-compose.

docker-compose down -v --rmi all

"-v" is for all the volumes

"--rmi all" is for all the images