Multihunter
Multihunter

Reputation: 5948

How to get docker container id when starting container

When writing a bash script that starts a docker container, it is useful to refer to the started docker container. How do you get the specific container id of a docker container when you start it?

P.S. I know that I can use --name to name the container, which I can use to filter the list of containers using docker ps -aqf "name=containername", but this will fail if I ever start the script twice. And then there's the possibility of name conflicts. Besides, what's the point of container IDs if you can't use them?

Upvotes: 6

Views: 6167

Answers (2)

Shon
Shon

Reputation: 4098

In the documentation for docker run under "capture container id", they advise using the --cidfile flag for this purpose.

--cidfile takes a file name as an argument and will write the long ID of the container to that location. E.g.,

docker run --cidfile /tmp/hello-world.cid hello-world && cat /tmp/hello-world.cid

This is useful when you don't want to run the image in a detached state, but still want access to the ID.

Upvotes: 5

Multihunter
Multihunter

Reputation: 5948

When you start a detached container, it returns the container ID. e.g.:

$ docker run -d ubuntu:18.04
71329cf6a02d89cf5f211072dd37716fe212787315ce4503eaee722da6ddf18f

In bash, you can define a new variable from the output like this:

CID=$(docker run -d ubuntu:18.04)

Then, later you can use this variable to refer to your container like this:

docker stop $CID
docker rm $CID

Upvotes: 8

Related Questions