Docker + Bash
Some tips and helpers for Docker :
Remove all containers
We use docker ps --all
to list all containers.
We use docker rm --force <container>
to remove a container.
To remove all containers silently we can execute :
$ docker rm --force $(docker ps --all --quiet) &>/dev/null
Let’s make our life easier by adding a bash function in the ~/.bashrc
file :
drc means docker remove containers.
# docker: remove all containers (running, exited, ...) silently
drc() { docker rm --force $(docker ps --all --quiet) &>/dev/null; }
Now you can reload the run commands file and execute the drc function :
$ . ~/.bashrc
$ drc
Remove all images
We use docker images --all
to list all images.
We use docker rmi --force <image>
to remove an image.
To remove all images silently we can execute :
$ docker rmi --force $(docker images --all --quiet) &>/dev/null
Let’s make our life easier by adding a bash function in the ~/.bashrc
file :
dri means docker remove images.
We can notice that the function invokes the drc function.
# docker: remove all images silently
dri() { drc; docker rmi --force $(docker images --all --quiet) &>/dev/null; }
Now you can reload the run commands file and execute the dri function :
$ . ~/.bashrc
$ dri
Remove dangling images
Docker images consist of multiple layers. Dangling images are layers that have no relationship to any tagged images. They no longer serve a purpose and consume disk space.
We use docker images --filter dangling=true
to list untagged images.
Untagged images are those with the <none>
label :
$ docker images --filter dangling=true
REPOSITORY TAG IMAGE ID CREATED SIZE
<none> <none> 71b672f83ce6 About an hour ago 5.55MB
<none> <none> e47393887344 About an hour ago 5.55MB
<none> <none> c038e3c9b034 About an hour ago 5.55MB
To remove all untagged images silently we can execute :
$ docker rmi --force $(docker images --filter dangling=true --quiet) &>/dev/null
Let’s make our life easier by adding a bash function in the ~/.bashrc
file :
drd means docker remove dangling images.
# docker: remove all dangling (untagged) images silently
drd() { docker rmi --force $(docker images --filter dangling=true --quiet) &>/dev/null; }
List the last 10 tags of a docker image
We can see the images of alpine on the docker hub site.
We can get the JSON data of the 10 latests images from the registry API page.
We can list the latests tags from the terminal by using curl and jq :
# the last 10 tags of the `alpine` image
$ curl --silent 'https://registry.hub.docker.com/v2/repositories/library/alpine/tags/' \
| jq --raw-output '."results"[]["name"]'
Let’s make our life easier by adding a bash function in the ~/.bashrc
file :
dlt means docker list tags.
# docker: list the last 10 tags of an image.
# sample usage: `dlt alpine`
dlt() { curl --silent "https://registry.hub.docker.com/v2/repositories/library/$1/tags/" | jq --raw-output '."results"[]["name"]' 2>/dev/null; }