Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

docker

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>"
like image 846
Nobita Avatar asked Sep 04 '17 06:09

Nobita


People also ask

Which command is useful to find the process ID of the running docker container?

Find the running container's ID by using the docker ps command.

Which command is used to return currently running container IDS?

One can list all of the containers on the machine via the docker ps command. This command is used to return the currently running containers.

How do I name my docker container when running?

How to Name a Docker Container. You can assign memorable names to your docker containers when you run them, using the --name flag as follows. The -d flag tells docker to run a container in detached mode, in the background and print the new container ID.


2 Answers

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 ...
like image 181
yamenk Avatar answered Sep 16 '22 17:09

yamenk


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

like image 30
QNimbus Avatar answered Sep 16 '22 17:09

QNimbus