Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

If I ran sudo doccker ps I got this

[user@vm1 ~]$ sudo docker ps 

CONTAINER ID        IMAGE                          COMMAND                  CREATED                  STATUS                  PORTS                        NAMES
e8ff73dec1d5        portal-mhn:latest         "nginx -g 'daemon of…"   43 minutes ago           Up 43 minutes  portal-mhn_portal-mhn.1.4rsfv94wy97gb333q3kfyxz32
62a7cf09d7bf        portal-admin:latest       "nginx -g 'daemon of…"   43 minutes ago           Up 43 minutes  portal-admin_portal-admin.1.s62iep4gl5g5oj2hrap14kz1t  

I'm trying to grab the container ID base on ImageName.

Ex. Is there away to grab the container id of portal-mhn:latest via a command line ? which is e8ff73dec1d5

like image 593
Tiffany Soun Avatar asked Jan 08 '19 19:01

Tiffany Soun


2 Answers

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.

like image 181
lee-pai-long Avatar answered Oct 18 '22 14:10

lee-pai-long


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).

like image 9
Yu Chen Avatar answered Oct 18 '22 14:10

Yu Chen