进入docker容器

docker容器中没有sshd服务,我们可以使用nsenter来进入到容器中操作

nsenter项目地址:https://github.com/jpetazzo/nsenter

如果你的系统中没有nsenter命令,可以安装下

装好之后,vim docker-enter 内容如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/bin/sh

if [ -e $(dirname "$0")/nsenter ]; then
# with boot2docker, nsenter is not in the PATH but it is in the same folder
NSENTER=$(dirname "$0")/nsenter
else
NSENTER=nsenter
fi

if [ -e $(dirname "$0")/importenv ]; then
# with boot2docker, importenv is not in the PATH but it is in the same folder
IMPORTENV=$(dirname "$0")/importenv
else
IMPORTENV=importenv
fi

if [ -z "$1" ]; then
echo "Usage: `basename "$0"` CONTAINER [COMMAND [ARG]...]"
echo ""
echo "Enters the Docker CONTAINER and executes the specified COMMAND."
echo "If COMMAND is not specified, runs an interactive shell in CONTAINER."
exit
fi

PID=$(docker inspect --format "{{.State.Pid}}" "$1")
[ -z "$PID" ] && exit 1
shift

if [ "$(id -u)" -ne "0" ]; then
which sudo > /dev/null
if [ "$?" -eq "0" ]; then
LAZY_SUDO="sudo "
else
echo "Warning: Cannot find sudo; Invoking nsenter as the user $USER." >&2
fi
fi

ENVIRON="/proc/$PID/environ"

# Prepare nsenter flags
OPTS="--target $PID --mount --uts --ipc --net --pid --"

# env is to clear all host environment variables and set then anew
if [ $# -lt 1 ]; then
# No arguments, default to `su` which executes the default login shell
$LAZY_SUDO "$IMPORTENV" "$ENVIRON" "$NSENTER" $OPTS su -m root
else
# Has command
# "$@" is magic in bash, and needs to be in the invocation
$LAZY_SUDO "$IMPORTENV" "$ENVIRON" "$NSENTER" $OPTS "$@"
fi

给此文件赋予执行权限,并放入到$PATH目录下

1
2
> chmod +x docker-enter
> mv docker-enter /usr/bin/

执行以下命令即可进入docker

1
> docker-enter <container-id>