I swear I've used an option some time ago where you can launch a container, then in the next docker command you can do something with that container without explicitly referring to its ID or alias - either it is "the first container in your list of containers" or "most recently created container". But I can't find anything on Google.
My imagination is recalling something like this:
docker run --detach -it ubuntu:latest
docker exec -it {0} bash
Is there any such thing? This is useful when you want to share instructions with someone for spinning something up without them having to copy and paste (or type) whatever their specific container ID was.
The docker exec command runs a new command in a running container. The command started using docker exec only runs while the container's primary process ( PID 1 ) is running, and it is not restarted if the container is restarted. COMMAND will run in the default directory of the container.
Running Commands as a Different User in a Docker Container To run a command as a different user inside your container, add the --user flag: docker exec --user guest container-name whoami.
Follow these steps: Use docker ps to get the name of the existing container. Use the command docker exec -it <container name> /bin/bash to get a bash shell in the container. Or directly use docker exec -it <container name> <command> to execute whatever command you specify in the container.
Find the running container's ID by using the docker ps command. Find the PID number of the first process in the running container by running the docker inspect command. Enter the running container by using the nsenter command.
Collecting the several solutions, here are some approaches (feel free to update the answer with yours):
This is probably the most compact solution
docker run --detach --name my_container -it ubuntu:latest
docker exec -it my_container bash
This is the one I had been recalling.
docker run --detach -it ubuntu:latest
docker exec -it $(docker ps --latest --quiet) bash
# you can also filter by ancestor (image) if other containers have been launched
# in the meanwhile:
docker exec -it $(docker ps --latest --quiet --filter ancestor=ubuntu:latest) bash
I don't fully understand how $_
would help in this case so can't give an example.
You don't have to copy the entire ID. If you type a
as the container ID it will find the container starting with that character sequence. If there are multiple matches and the command can accept multiple container IDs it will still work (e.g. docker kill a
will kill all containers with IDs that start with the letter a
)
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