Get shell in running Docker container

Mattias Geniar, Sunday, October 15, 2017

This has saved me more times than I can count, having the ability to debug a running container the way you would in a "normal" VM.

First, see which containers are running;

$ docker ps
CONTAINER ID        IMAGE               COMMAND                  [...] NAMES
925cc10d55df        66cc85c3f275        "gitlab-runner-ser..."   [...] runner-f500bed1-project-3888560-concurrent-0-mysql-0-wait-for-service
0ab431ea0bcf        3e3878acd190        "docker-entrypoint..."   [...] runner-f500bed1-project-3888560-concurrent-0-mysql-0
4d9de6c0fba1        nginx:alpine        "nginx -g 'daemon ..."   [...] nginx-container

To get a shell (Bash) on a container of choice, run this;

$ docker exec -i -t nginx-container /bin/bash

The nginx-container determines which container you want to enter, it's the name in the last column of the docker ps output.

Alternatively, use the container ID;

$ docker exec -i -t 4d9de6c0fba1 /bin/bash

Don't use docker attach, as that'll give you funky results if the initial command that's started in a Docker container is something like MongoDB or Redis, the instance will be killed.

Hi! My name is Mattias Geniar. I'm a Support Manager at Nucleus Hosting in Belgium, a general web geek & public speaker. Currently working on DNS Spy & Oh Dear!. Follow me on Twitter as @mattiasgeniar.

Share this post

Did you like this post? Will you help me share it on social media? Thanks!


Ward Kennes Monday, October 16, 2017 at 10:16 - Reply

Great! Even a little more shorthand you can do:

docker exec -it 4d9de6c0fba1 bash

Dominic Sunday, October 22, 2017 at 09:55 - Reply

Bash is not always installed in a minimal container image. You.might add dash (‘sh’) as an alternative.

Dominic Sunday, October 22, 2017 at 09:57 - Reply

And the options ‘-i -t’ can be shortened to ‘-it’. Saves you some key strokes.

Devis Lucato Monday, October 23, 2017 at 04:35 - Reply

You can also shorten the hash to the first few chars, as long as they identify a unique instance, e.g. in your screenshot you can run “docker exec -it 4 bash”, where “4” uniquely identifies “4d9de6c0fba1”

Bert Van Vreckem Tuesday, October 24, 2017 at 10:51 - Reply

I have created the following alias for this:

alias dS=’docker exec –interactive –tty $(docker ps –latest –quiet) env TERM=xterm /bin/bash’

See for more

mlen Monday, October 30, 2017 at 12:26 - Reply

docker exec -ti sh doesn’t allow to attach to other processes in the container with a debugger (even when launched with privileged flag). Spawning a shell with this script allows to do so:

Leave a Reply

Your email address will not be published. Required fields are marked *