Remove all stopped containers: "docker rm" requires at least 1 argument

Viewed 17379

I'm reading a book on docker. It is a couple of years old.

I'll cite:

If you want to get rid of all your stopped containers, you can use
the output of docker ps -aq -f status=exited , which gets the
IDs of all stopped containers. For example:
$ docker rm -v $(docker ps -aq -f status=exited)

When I run this, I get:

michael@michael-desktop:~$ sudo docker rm -v $(docker ps -aq -f status=exited)
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.30/containers/json?all=1&filters=%7B%22status%22%3A%7B%22exited%22%3Atrue%7D%7D: dial unix /var/run/docker.sock: connect: permission denied
"docker rm" requires at least 1 argument(s).
See 'docker rm --help'.

Usage:  docker rm [OPTIONS] CONTAINER [CONTAINER...]

Remove one or more containers

Could you help me understand what should I do to gain what is intended.

5 Answers
$ sudo docker rm -v $(docker ps -aq -f status=exited)
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.30/containers/json?all=1&filters=%7B%22status%22%3A%7B%22exited%22%3Atrue%7D%7D:
dial unix /var/run/docker.sock: connect: permission denied
"docker rm" requires at least 1 argument(s).
See 'docker rm --help'.

The permission denied message comes from the embedded docker ps command. It is run by the shell outside of your parent sudo command, and the output is passed to sudo to run the docker rm as root. There are several fixes.

The easy option, run the docker ps with sudo:

$ sudo docker rm -v $(sudo docker ps -aq -f status=exited)

Option two is to run an entire shell as root:

$ sudo -s
# docker rm -v $(docker ps -aq -f status=exited)
# exit

Or you can give your user access to the docker socket so sudo is no longer needed:

$ sudo usermod -aG docker $USER
$ newgrp docker

The above is a one time change, and gives that user root access implicitly with docker. Then you can run:

$ docker rm -v $(docker ps -aq -f status=exited)

Actually its an rights issue.... the error message:

Got permission denied while trying to connect to the Docker daemon socket at unix://

Tells you that you cant connect to you docker daemon which is running under root. You should decide if you want to use docker with # sudo or as root user.

Manage Docker as a non-root user

Further as said the docker rm complains about no images found for deletion therefore it wouldn't possible to delete images.

The command docker rm $(docker ps -aq -f status=exited) is just fine with newest docker version 18.09.0 but you could use docker container prune as well that is the more interactive way.

Related