实测可用,进入容器的两种办法。

在学习docker的过程中,虽然可以使用k8s进行相应的管理,但还是会遇到很多的需要进入容器的情况,方法如下:

1.使用nsenter:

在大多数Linux发行版中,util-linux包中含有nsenter.如果没有,你需要安装它.

cd /tmp
curl https://www.kernel.org/pub/linux/utils/util-linux/v2.24/util-linux-2.24.tar.gz \
	| tar -zxf-
cd util-linux-2.24 ./configure --without-ncurses make nsenter cp nsenter /usr/local/bin 

使用shell脚本 docker-enter,将如下代码保存为docker-enter, chomod +x docker-enter

#!/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> ,这样就进入到指定的容器中。

2.命令exec

docker在1.3.X版本之后还提供了一个新的命令exec用于进入容器,这种方式相对更简单一些,下面我们来看一下该命令的使用:

  sudo docker exec --help   

  sudo docker ps  

  sudo docker exec -it 775c7c9ee1e1 /bin/bash  

猜你喜欢

转载自www.cnblogs.com/xiaoyuxixi/p/11220581.html