NotSoShabby
NotSoShabby

Reputation: 3688

Dynamically get docker image id from its name

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?

Upvotes: 10

Views: 19713

Answers (3)

jp48
jp48

Reputation: 1356

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.

Upvotes: 21

David Maze
David Maze

Reputation: 158908

docker rmi will never delete an image that corresponds to a running container. So if you have a container based on postgres running, and you want to delete every other image on your system, the age-old incantations will do what you want; I’m too old-school for docker system but the “get all of the image IDs, then try to delete them all” I know is

docker images -q | xargs docker rmi

Which will print out some errors, but will delete all of the images it can.

Upvotes: 2

KamilCuk
KamilCuk

Reputation: 140990

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

Upvotes: 17

Related Questions