Nobita
Nobita

Reputation: 708

Dynamically get a running container id/name created by docker run command

So I'm trying to run the following shell script which requires the container id/name of the container (in which the script would be run) dynamically.

One way could be to do docker ps and then getting the Container Id, but that won't be dynamic.

So is there a way to do this dynamically?

#!/bin/bash
docker exec <container id/name> /bin/bash -c "useradd -m <username> -p <password>"

Upvotes: 32

Views: 30668

Answers (3)

dgo
dgo

Reputation: 3937

I just figured out a way to do this that works for this. I'm constantly going into my container in bash, but each time I do it I have to look up the id of the running container - which is a pain. I use the --filter command like so:

docker ps -q --filter="NAME={name of container}"

Then the only thing that's output is the id of the container, which allows me to run:

docker exec -it $(docker ps -q --filter="NAME={name of container}") bash

...which is what I really want to do in this case.

You can filter by

id, name, label, exited, status, ancestor, 
beforesince, volume, network, publishexpose, 
health,isolation, or is-task

The documentation for filter is here.

Upvotes: 9

QNimbus
QNimbus

Reputation: 385

You can start your container and store the container id inside a variable like so:

container_id=$(docker run -it --rm --detach busybox)

Then you can use the container id in your docker exec command like so:

docker exec $container_id ls -la

or

docker stop $container_id

Note: Not using a (unique) name for the container but using an ID instead is inspired by this article on how to treat your servers/containers as cattle and not pets

Upvotes: 24

yamenk
yamenk

Reputation: 51778

You can give your container a specific name when running it using --name option.

docker run --name mycontainer ...

Then your exec command can use the specified name:

docker exec -it mycontainer ...

Upvotes: 33

Related Questions