2

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?

stevec
  • 41,291
  • 27
  • 223
  • 311

2 Answers2

2

You can specify a name for the running container and reference it that way.

docker run --name mycontainer -d myimage
docker exec -it mycontainer bash

You can also spawn a container and jump right into a shell.

docker run --name mycontainer --rm --entrypoint="" -it myimage bash

Or, you can run a single command inside the container and then exit.

docker run --name mycontainer --rm --entrypoint="" myimage echo "Hello, World!"
Garrett Hyde
  • 5,409
  • 8
  • 49
  • 55
0

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 any The container name xxxx is already in use errors:

{ docker stop $(docker ps -a -q) } || {} && \
docker container prune -f && \
docker build -t myimage . && \
docker run --name mycontainer -dt myimage && \
docker exec -it mycontainer bash

Warning

The docker stop $(docker ps -a -q) part will stop all running containers

AND

The docker container prune -f will remove all stopped containers

So please be careful and make sure you're okay with both of those things happening before using this.

Notes

  • A nice benefit to this is you can edit a Dockerfile then pres Up in the terminal and hit enter to rerun the command which will rebuild/run/shell into the new container.
stevec
  • 41,291
  • 27
  • 223
  • 311