简体   繁体   中英

docker volume prune: Dont delete named volumes

I have created a volume

docker volume create postgresql_db

Now i am using it in my docker-compose.xml

services:
  postgresql:
    image: "postgres:11-alpine"
    volumes:
      - type: volume
        source: postgresql_data
        target: /var/lib/postgresql/data
        volume:
          nocopy: true        
    environment:
      PGDATA: '/var/lib/postgresql/data/pgdata'
    networks:  # connect to the bridge
      - postgresql_network
    command: ["postgres", "-c", "log_statement=all","-c", "log_destination=stderr"]

volumes: 
  postgresql_data:
    external: true

Sometimes i want to stop and clean the docker system.

So I try to run

docker stop $(docker ps -aq) # stop all containers 
docker rm $(docker ps -a -q) # remove all containers
docker container prune
docker image prune
docker network prune
docker volume prune  #<-- remove all dangling volumes also

this also delete postgresql_data ie named volume

how to avoid that.

There's no option to the docker volume prune command for this. There's also no metadata on the volume that indicates it's an anonymous volume, it's just a named volume with a random hex name. The best I do is list the dangling volumes and delete the ones with a long hex name. As long as your named volumes are not exactly 64 hex characters, they won't be included in this:

docker volume ls -qf dangling=true | egrep '^[a-z0-9]{64}$' | \
  xargs --no-run-if-empty docker volume rm

Well, according to Docker's documentation , you can simply filter your volumes (by label, for instance):

docker volume prune --filter label!=postgresql_db

then all volumes that are not (look at the ! ) named postgresql_db and are not attached to 1 or more containers will be removed.

It worked for me. Delete all unnamed volumes:

docker volume prune --filter "label!=com.docker.compose.volume"

docker rm offers the flag -v which is deleting all anonymous volumes corresponding to this container.

If you want to prune the dangling ones as well (not associated to any container you're currently running) do the docker volume prune before stopping and removing the running ones.

Therefore:

docker volume prune  #<-- remove all dangling volumes also
docker stop $(docker ps -aq) # stop all containers 
docker rm -v $(docker ps -a -q) # remove all containers
docker container prune
docker image prune
docker network prune

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM