How to obtain container id base on docker image name via command line ?

The accepted answer works, but you might possibly have a misnamed container name that has postgres in its name but is actually running a totally different image, since the answer only uses grep to look for matching lines.

You can use Docker's built in filter flag:

docker ps --filter "ancestor=postgres" -q

as an alternative. The -q flag indicates to only return the container ID (quiet mode).


If you want to get the container id based on the image name this should work:

$ docker ps | grep '<image_name>' | awk '{ print $1 }'

Or even:

$ docker ps | awk '/<image_name>/ { print $1 }'

As others have suggested you can also directly filter by the image name using the ancestor filter:

$ docker ps -aqf "ancestor=<image_name>"

This has the advantage of being string on the image_name value instead of looking for a matching pattern. Thanks to @kevin-cui and @yu-chen.


I needed only to obtain the latest running container id by image name, including stopped containers:

docker ps -a | grep 'django-content-services:' -m 1 | awk '{ print $1 }'

In docker -a to include all containers (even stopped). In grep, -m so grep only matches the first case. Cheers!