Get docker container id from container name

后端 未结 9 1668
無奈伤痛
無奈伤痛 2020-12-12 11:48

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

9条回答
  •  死守一世寂寞
    2020-12-12 12:00

    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]]

提交回复
热议问题