How to get bash or ssh into a running container in background mode?
I want to ssh or bash into a running docker container. Please, see example:
$ sudo docker run -d webserver
webserver is clean image from ubuntu:14.04
$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
665b4a1e17b6 webserver:latest /bin/bash ... ... 22/tcp, 80/tcp loving_heisenberg
Now I want to get something like this (go into the running container):
$ sudo docker run -t -i webserver
(or maybe 665b4a1e17b6
instead)$ root@665b4a1e17b6:/#
However when I run the line above I get new CONTAINER ID:
$ root@42f1e37bd0e5:/#
I used Vagrant and I'd like to get a similar behaviour as vagrant ssh
.
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.