简体   繁体   中英

Failing to remove stopped Docker container

I am trying to forcefully stop and remove all Docker images:

docker stop $(docker ps -a -q) && docker rm -f $(docker ps -a -q) && docker rmi -f $(docker images -a -q)

However, I receive:

Error response from daemon: conflict: unable to delete 3b5b05d98767 (cannot be forced) - image is being used by running container deedefb82e27 .

As far as I understand, the container is restarting faster than the command tries to delete it.

The error is in removing the image, not the container. This is either a race condition from the container not being completely deleted yet, or you have something else starting containers on the system like swarm mode.

For a race condition, just add a few seconds between the commands to give the rm time to finish on the server. Also there's no need for a stop since you're doing an rm -f :

docker rm -f $(docker ps -a -q) \
&& sleep 2 && docker rmi -f $(docker images -a -q)

If you have containers running in swarm mode, first remove your stacks and services that you don't want to have running:

# something like this, will only work if you have stacks defined
docker stack rm $(docker stack ls --format '{{.Name}}')

# similar command for services
docker service rm $(docker service ls -q)

Each of those may take 10 seconds for the containers to exit, plus a few more seconds for the swarm manager to send the command, so you may want a sleep 15 after they both return to give the server time to complete the request.

You may have to preface all of your commands with sudo , or ensure that you are already in a root shell.

For example:

sudo docker stop $(sudo docker ps -a -q) && sudo docker rm -f $(sudo docker ps -a -q) && sudo docker rmi -f $(sudo docker images -a -q)

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