I often do the following:
docker run -dt myimage
docker ps # This step gives the container id necessary for next step
docker exec -it <container-id> bash
Ideally I’d like to do it all in one line
docker run -dt myimage && docker exec -it <id> bash
but I don’t know how to get the container id to docker exec
without looking it up in a separate step.
Question
Is there a one-liner to run an image and shell into its container?
2
Answers
To take @GarretHyde's great answer a little further, here's a nice sequence of commands (that can be run as a single line with a few
&&
s) and will avoid anyThe container name xxxx is already in use
errors:Warning
The
docker stop $(docker ps -a -q)
part will stop all running containersAND
The
docker container prune -f
will remove all stopped containersSo please be careful and make sure you're okay with both of those things happening before using this.
Notes
You can specify a name for the running container and reference it that way.
You can also spawn a container and jump right into a shell.
Or, you can run a single command inside the container and then exit.