Docker – How to remove dangling images in Docker

docker

How can I remove dangling Docker images? I tried

sudo docker rmi $(docker images -f "dangling=true" -q)

but it shows

Got permission denied while trying to connect to the Docker daemon
socket at unix:///var/run/docker.sock: Get
http://%2Fvar%2Frun%2Fdocker.sock/v1.35/images/json?filters=%7B%22dangling%22%3A%7B%22true%22%3Atrue%7D%7D:
dial unix /var/run/docker.sock: connect: permission denied

Best Answer

Both docker commands require sudo otherwise the docker images list will run first as your user.

sudo docker rmi $(sudo docker images -f "dangling=true" -q)

Sometimes sudo doesn't work properly when run like this for the docker images query and you need to run the entire command under a single sudo:

sudo sh -c 'docker rmi $(docker images -f "dangling=true" -q)'