11

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

Tiffany Soun
  • 493
  • 2
  • 9
  • 18
  • 2
    Filter by IMAGE name `sudo docker ps -aqf "ancestor=portal-mhn:latest "` https://stackoverflow.com/questions/34496882/get-docker-container-id-from-container-name – Kevin Cui Jan 08 '19 at 20:40

3 Answers3

17

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.

lee-pai-long
  • 1,927
  • 14
  • 16
9

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

Yu Chen
  • 5,056
  • 5
  • 39
  • 76
1

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!

radtek
  • 30,748
  • 10
  • 135
  • 106