概述

使用docker创建了容器之后,大家比较关心的就是如何在宿主机中访问容器,进入docker容器的方法有好几种,这里就罗列下我知道的几种方式。进入docker容器的比较常见的方式如下:

  • 使用docker attach container
  • 使用ssh
  • 使用nsenter
  • 使用exec

使用docker attach方式进入容器

Docker提供了attach命令来进入容器.docker attach的help如下

1
2
3
4
5
6
7
8
9
Usage:  docker attach [OPTIONS] CONTAINER

Attach to a running container

Options:
--detach-keys string Override the key sequence for detaching a container
--help Print usage
--no-stdin Do not attach STDIN
--sig-proxy Proxy all received signals to the process (default true)

我们首先创建一个运行在守护态的docker容器,然后使用docker attach命令进入该容器

1
2
//启动一个docker容器
docker run -itd saltstack/ubuntu-14.04 /bin/bash

使用docker ps -a查看该容器的容器id,结果如下:
docker_ps_a

这里我们可以看到该容器的id为43bdf46c62e1,这时候我们就可以执行docker attach 43bdf46c62e1命令来进入刚刚启动的容器,如图所示:
docker_attach_43bdf

但是使用docker attach命令会有一个副作用。当多个窗口使用该命令进入43bdf46c62e1r容器的时候所有的窗口都会同步显示。如果有一个窗口阻塞了,那么其他的窗口再也无法进行其他的操作。多个窗口同步显示如图所示:
docker_attach_same

使用ssh的方式进入docker容器

对于容器的使用,除了attach命令之外,比较容易想到的就是使用ssh的方式连接容器,在容器中安装ssh server,这样就能保证多人进入容器且互不干扰。关于为什么不建议使用,请参考这篇文章:Why you don’t need to run SSHd in your Docker containers。(英文不好可以看到中文版

使用nsenter进入Docker容器

在上面两种方式都不适合的情况下,还有一种比较方便的方法,即使用nsenter进入Docker容器。关于什么是nsenter请参考nsenter github repo.
安装nsenter

1
2
3
4
5
6
wget https://www.kernel.org/pub/linux/utils/util-linux/v2.24/util-linux-2.24.tar.gz
tar -xzvf util-linux-2.24.tar.gz
cd util-linux-2.24/
./configure --without-ncurses
make nsenter
sudo cp nsenter /usr/local/bin

下面的话,我们需要使用nsenter进入容器内部。首先我们需要获取容器的PID号。这里如果通过执行docker inspect 31ced27e1684 来获取容器的PID号为44543。然后通过改PID号,执行nsenter --target 44543 --mount --uts --ipc --net --pid
如下图所示:
docker_nsenter

使用exec进入容器

除了上面的做法之外,docker在1.3.x版本之后还提供了一种新的方式进入容器。这种方式相对简单

1
2
3
4
5
6
7
8
9
10
11
12
13
docker exec --help

Usage: docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

Run a command in a running container

-d, --detach Detached mode: run command in the background
--detach-keys Override the key sequence for detaching a container
--help Print usage
-i, --interactive Keep STDIN open even if not attached
--privileged Give extended privileges to the command
-t, --tty Allocate a pseudo-TTY
-u, --user Username or UID (format: <name|uid>[:<group|gid>])

接下来,我们通过exec来进入一个已经在运行的容器

1
2
3
4
//查看已经在运行的容器ID
docker ps -a
//通过exec命令对指定的容器执行bash
docker exec -it 31ced27e1684 /bin/bash

如图所示:
docker_exec