怎样在后台模式中登录一个docker容器的bash?

Ask Ubuntu上有人问怎么能login或者ssh一个运行的docker容器。
例如

1
2
3
4
5
$ 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

想进行这样的登录:

1
2
3
4
$ 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:/#

答案是 attach或者最新的exec

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

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

UPDATE: (docker >= 1.3) Thanks to WiR3D user who suggested another way to get container's shell. If we use attach we can use only one instance of shell. So if we want open new terminal with new instance of container's shell, we just need run the following:

1
2
3
4
$ sudo docker exec -i -t 665b4a1e17b6 bash #by ID
or
$ sudo docker exec -i -t loving_heisenberg bash #by Name
$ root@665b4a1e17b6:/#