16
votes

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

4

4 Answers

20
votes

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)'
14
votes

Docker has a build-in command to cleanup dangling images.

sudo docker image prune

To cleanup unused images and dangling ones, use:

sudo docker image prune -a
0
votes

Simply do

docker image prune

It will ask you to confirm

WARNING! This will remove all dangling images.
Are you sure you want to continue? [y/N]

Type y, you're done...

0
votes

As @Matt mentioned, you are missing sudo in inner command. Below will work

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

To get rid of using sudo everytime, give docker user permissions. Follow below steps

  1. Create the docker group.

    $ sudo groupadd docker
    
  2. Add your user to the docker group.

    $ sudo usermod -aG docker $USER