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>"
Find the running container's ID by using the docker ps command.
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 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.
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 ...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With