PatS
PatS

Reputation: 11524

How can I get (using a script) the ID to use with docker exec?

After a docker image is running, how can I programmatically get the ID so I can script commands for that image? I think the ID I want is called the Container ID because that is how it is listed in the output of the docker ps command.

For example, I start the image using docker run, I run the docker ps command to get the "ID" I want and then I can run docker logs or other commands.

docker run myImage
docker ps
CONTAINER ID  IMAGE       COMMAND     CREATED 
1234567890    myImage     sleep 120   ...

So now that I know the container ID is 1234567890, I can run commands on the container.

docker logs 1234567890
docker exec -it 1234567890 bash

How can I get that ID programmatically (assuming that there is only one instance of that image currently running).

I tried this command that I thought would work but it did not.

docker inspect --format='{{.Id}}' myImage
sha256:95e11.....

See also https://docs.docker.com/engine/reference/commandline/inspect/#examples.

I think the inspect only inspecting the "image" not the instance running (aka the container).

I hope I have the terminology right, but if not let me know and I'll fix it.

NOTE: If it matters, the script is a bash script on Linux.

Upvotes: 0

Views: 149

Answers (3)

Corey
Corey

Reputation: 1382

You can get container ID by filtering which created from particular image.

docker ps -qf "ancestor=imagename"

ancestor: filter containers which share a given image as an ancestor

-q: output only the ID

-f: for filtering

-l: show the latest

Upvotes: 0

Rmahajan
Rmahajan

Reputation: 1371

Also you can do in this way

for container_id in $(docker ps  --filter="name=$myImage" -q -a);do docker rm $container_id;done

Upvotes: 0

larsks
larsks

Reputation: 312370

If you start a detached container (docker run -d ...), the docker client will emit the container ID on stdout. So you can do something like:

$ CONTAINER_ID=$(docker run -d myImage)
$ docker exec $CONTAINER_ID somecommand

If you assign your container a name, you can use that in place of the container ID:

$ docker run --name myContainer myImage
$ docker exec myContainer somecommand

If you simply want the ID of the most recent container you launched, you can use docker ps -lq:

$ CONTAINER_ID=$(docker ps -lq)
$ docker exec $CONTAINER_ID somecommand

If there is only a single container running from a given image, you can run something like:

$ CONTAINER_ID=$(docker container ps --filter ancestor=myImage -q)
$ docker exec $CONTAINER_ID somecommand

Upvotes: 3

Related Questions