`

Docker - nsenter

阅读更多
【基本介绍】
这里我们介绍docker的nsenter命令安装和使用。在大多数Linux发行版中,util-linux包中含有nsenter.
nsenter - run program with namespaces of other processes

【安装】
源码安装
$ 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


yum安装
[root@localhost tmp]# yum install util-linux
Loaded plugins: fastestmirror, refresh-packagekit, security
Loading mirror speeds from cached hostfile
 * base: mirrors.zju.edu.cn
 * epel: ftp.riken.jp
 * extras: mirrors.163.com
 * updates: mirrors.163.com
Setting up Install Process
Package util-linux-ng-2.17.2-12.18.el6.x86_64 already installed and latest version
Nothing to do


【nsenter连接容器】
为了连接到容器,你还需要找到容器的第一个进程的 PID,可以通过下面的命令获取。

PID=$(docker inspect --format "{{ .State.Pid }}" <container>)


通过这个 PID,就可以连接到这个容器:

$ nsenter --target $PID --mount --uts --ipc --net --pid



可运行脚本
#!/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 [ -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."
  else
    PID=$(docker inspect --format "{{.State.Pid}}" "$1")
    if [ -z "$PID" ]; then
      exit 1
    fi
    shift

    OPTS="--target $PID --mount --uts --ipc --net --pid --"

    if [ -z "$1" ]; then
      # No command given.
      # Use su to clear all host environment variables except for TERM,
      # initialize the environment variables HOME, SHELL, USER, LOGNAME, PATH,
      # and start a login shell.
      "$NSENTER" $OPTS su - root
    else
      # Use env to clear all host environment variables.
      "$NSENTER" $OPTS env --ignore-environment -- "$@"
    fi
  fi

运行 docker-enter <container id> ,这样就进入到指定的容器中。

更简单的,建议大家下载 .bashrc_docker,并将内容放到 .bashrc 中。
$ wget -P ~ https://github.com/yeasy/docker_practice/raw/master/_local/.bashrc_docker;
$ echo "[ -f ~/.bashrc_docker ] && . ~/.bashrc_docker" >> ~/.bashrc; source ~/.bashrc

这个文件中定义了很多方便使用 Docker 的命令,例如 docker-pid 可以获取某个容器的 PID;而 docker-enter 可以进入容器或直接在容器内执行命令。
$ echo $(docker-pid <container>)
$ docker-enter <container> ls


【参考】
http://www.tuicool.com/articles/eYnUBrR
http://yeasy.gitbooks.io/docker_practice/content/container/enter.html
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics