Get docker container id from container name

2019-01-30 10:27发布

问题:

What is the command to get the docker container id from the container name?

回答1:

In Linux:

sudo docker ps -aqf "name=containername"

Or in OS X:

docker ps -aqf "name=containername"

where containername is your container name

explanation:

  • -q for quiet. output only the ID
  • -a for all. works even if your container is not running
  • -f for filter.


回答2:

You can try this:

docker inspect --format="{{.Id}}" container_name

This approach is OS independent.



回答3:

  1. Get container Ids of running containers ::

    $docker ps -qf "name=IMAGE_NAME"
    
        -f: Filter output based on conditions provided
        -q: Only display numeric container IDs
    
  2. Get container Ids of all containers ::

    $docker ps -aqf "name=IMAGE_NAME"
    
        -a: all containers
    


回答4:

If you want to get complete ContainerId based on Container name then use following command

 docker ps --no-trunc -aqf name=containername


回答5:

The simplest way I can think of is to parse the output of docker ps

Let's run the latest ubuntu image interactively and connect to it

docker run -it ubuntu /bin/bash

If you run docker ps in another terminal you can see something like

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
8fddbcbb101c        ubuntu:latest       "/bin/bash"         10 minutes ago      Up 10 minutes                           gloomy_pasteur

Unfortunately, parsing this format isn't easy since they uses spaces to manually align stuff

$ sudo docker ps | sed -e 's/ /@/g'
CONTAINER@ID@@@@@@@@IMAGE@@@@@@@@@@@@@@@COMMAND@@@@@@@@@@@@@CREATED@@@@@@@@@@@@@STATUS@@@@@@@@@@@@@@PORTS@@@@@@@@@@@@@@@NAMES
8fddbcbb101c@@@@@@@@ubuntu:latest@@@@@@@"/bin/bash"@@@@@@@@@13@minutes@ago@@@@@@Up@13@minutes@@@@@@@@@@@@@@@@@@@@@@@@@@@gloomy_pasteur@@@@@@

Here is a script that converts the output to JSON.

https://gist.github.com/mminer/a08566f13ef687c17b39

Actually, the output is a bit more convenient to work with than that. Every field is 20 characters wide. [['CONTAINER ID',0],['IMAGE',20],['COMMAND',40],['CREATED',60],['STATUS',80],['PORTS',100],['NAMES',120]]



标签: docker