How to get bash or ssh into a running container in background mode?

The answer is Docker's attach command. So for my example above, the solution will be:

$ sudo docker attach 665b4a1e17b6 #by ID
or
$ sudo docker attach loving_heisenberg #by Name
$ root@665b4a1e17b6:/#

For Docker version 1.3 or later: Thanks to user WiR3D who suggested another way to get a container's shell. If we use attach we can use only one instance of the shell. So if we want open a new terminal with a new instance of a container's shell, we just need to run the following:

$ sudo docker exec -i -t 665b4a1e17b6 /bin/bash #by ID

or

$ sudo docker exec -i -t loving_heisenberg /bin/bash #by Name
$ root@665b4a1e17b6:/#

From Docker 1.3 onwards:

docker exec -it <containerIdOrName> bash

Basically, if the Docker container was started using the /bin/bash command you can access it using attach. If not, then you need to execute the command to create a Bash instance inside the container using exec.

Also to exit Bash without leaving Bash running in a rogue process:

exit

Yep, it is that simple.


Although the author of the question specifically said they are interested in a running container, it's also worth noting that if the container is not running, but you'd like to run it to poke around you can run:

docker run -i -t --entrypoint /bin/bash <imageID>