Docker exec command on most recent container without copying and pasting ID

Viewed 1566

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.

1 Answers

Collecting the several solutions, here are some approaches (feel free to update the answer with yours):

Hardcode the container name

This is probably the most compact solution

docker run --detach --name my_container -it ubuntu:latest
docker exec -it my_container bash

Get your most recently created docker container ID

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

Use a shell variable

I don't fully understand how $_ would help in this case so can't give an example.

Other tips for easier referencing

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)

Related