I would like to delete a Docker container and all associated images, volumes (not the external volumes) etc.

I looked around web but all the things I found were about getting rid of everything similar to docker system prune which is not what I want. I just want to get rid of stuff from a certain container.



There's only a single image for a container. If you remove it, and there are parent images that aren't otherwise used, docker will remove all the layers:

image_id=$(docker container inspect --format '{{.Image}}' "${container_name_or_id}")
vol_names=$(docker inspect --format '{{range .Mounts}}{{.Name}} {{end}}' "${container_name_or_id}")
docker container rm "${container_name_or_id}"
[ -n "${vol_names}" ] && docker volume rm ${vol_names}
docker image rm "${image_id}"

If you try to delete the image and it fails because it's in use, that's docker doing it's job for you. Image layers are shared among images and containers so that they are only written to disk once. If you still have a container or another image using those same layers, then deleting those shared layers would break other images and containers, and docker will block that for your safety.

| improve this answer | |
  • Thanks for the detailed reply. How about associated auto generated volumes if the docker run command created one or more? – yarun can Mar 16 '19 at 17:38
  • Script updated to cleanup volumes – BMitch Mar 16 '19 at 19:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.