Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically get docker image id from its name

Tags:

bash

docker

I need to dynamically delete all docker images in a server, except for the postgres image and container.

Now I need a dynamic way to get the id of that docker image so i will know to avoid it, using:

docker rmi $(docker images -q | grep -v $<id_of_postgres_container>)

For the container part, i managed to find this:

docker ps -aqf "name=postgres"

which returns only the id of the postgres container. Is there any way to do the same with images without getting too deep into bash scripting?

or any better suggestions?

like image 243
NotSoShabby Avatar asked Mar 20 '26 07:03

NotSoShabby


2 Answers

You can just use:

$ docker images -q [image_name]

Where image_name can contain tags (appended after :), registry username with / (if applicable), etc.

The image has to be downloaded for this to work, for example:

$ docker pull hello-world
...
Status: Downloaded newer image for hello-world:latest
docker.io/library/hello-world:latest
$ docker images -q hello-world
d1165f221234
$ docker images -q hello-world:latest
d1165f221234

If the image is not locally available, the only alternative I can think of is to manually query the registry, e.g. like this.

like image 110
jp48 Avatar answered Mar 22 '26 00:03

jp48


docker images --format="{{.Repository}} {{.ID}}" | 
grep "^postgres " | 
cut -d' ' -f2

Get docker images in the format repository<space>id, then filter lines starting with postgres<space>, then leave only id.

docker images --format="{{.Repository}} {{.ID}}" | 
grep "^postgres " | 
cut -d' ' -f2 | 
xargs docker rmi

But, if the postgres container and image is currently running or used, you can just:

 docker system prune --force --all
like image 30
KamilCuk Avatar answered Mar 21 '26 22:03

KamilCuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!