centos6中使用nsenter进入docker container例子

作者:袖梨 2022-06-30


最近一直搞docker,老是用exec进入docker容器也很麻烦,今天在网上发现了nsenter进入容器很方便,解放了老是使用命令进入docker容器的麻烦,下面来看看nsenter的安装和使用吧.
  系统:centos 6.x(64位)
  环境:docker 1.7.1
1.安装nsenter
wget https://www.kernel.org/pub/linux/utils/util-linux/v2.24/util-linux-2.24.tar.gz
tar zxf util-linux-2.24.tar.gz && cd util-linux-2.24
./configure --without-python --disable-all-programs --enable-nsenter --without-ncurses
make nsenter
cp nsenter /usr/local/bin

2.使用nsenter
#!/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 ps -a #获取docker的container的pid或者name
CONTAINER ID        IMAGE                        COMMAND                CREATED             STATUS              PORTS                                                                               NAMES
bf51a302046d        rocdk890/jenkins-nodejs:v1   "/bin/tini -- /usr/l   5 days ago          Up 4 days           0.0.0.0:3000->3000/tcp, 0.0.0.0:8080->8080/tcp, 0.0.0.0:8360->8360/tcp, 50000/tcp   jenkins_nodejs     
df85f816642c        bitnami/mongodb:3.2.5-0      "/entrypoint.sh"       2 weeks ago         Up 5 days           0.0.0.0:27017->27017/tcp                                                            mongodb

可以看到我这里有2个container运行在,然后使用刚刚docker-enter来进入container:
./docker-enter jenkins_nodejs

使用docker container的name来进入container是不是很方便,好了,有兴趣的朋友可以自己去研究下

相关文章

精彩推荐