在这里使用的OS是ubuntu16:04,所以不需要安装nsenter。
-
#运行一个容器
-
# docker run -itd ubuntu:16.04 /bin/bash
-
# docker ps
-
a5bb8d87ceff ubuntu:16.04 "/bin/bash" 14 minutes ago Up 9 minutes goofy_bartik
-
#
-
#为了连接到容器,需要找到容器的第一个进程(这里容器的第一个进程是/bin/bash)的PID
-
# PID=$(docker inspect --format "{{ .State.Pid }}" a5bb8d87ceff)
-
# nsenter --target $PID --mount --uts --ipc --net --pid
-
mesg: ttyname failed: No such file or directory
-
root@a5bb8d87ceff:/
-
-
-
或者下载.bashrc_docker脚本
-
# wget -P ~ https://github.com/yeasy/docker_practice/raw/master/_local/.bashrc_docker
-
# echo "[ -f ~/.bashrc_docker ] && . ~/.bashrc_docker" >> ~/.bashrc;source ~/.bashrc
-
# docker inspect --format '{{.State.Pid}}' a5bb8d87ceff
-
# docker inspect --format '{{ .NetworkSettings.IPAddress }}' a5bb8d87ceff
-
#查看容器第一个进程的pid
-
# echo $(docker-pid a5bb8d87ceff)
-
#进入容器
-
# docker-enter a5bb8d87ceff pwd
.bashrc_docker内容如下:
-
# Some useful commands to use docker.
-
# Author: yeasy@github
-
# Created:2014-09-25
-
-
#.bashrc_docker定义了docker-pid和docker-ip两个命令,为了方便查看pid和ip信息。
-
alias docker-pid="sudo docker inspect --format '{{.State.Pid}}'"
-
alias docker-ip="sudo docker inspect --format '{{ .NetworkSettings.IPAddress }}'"
-
-
#the implementation refs from https://github.com/jpetazzo/nsenter/blob/master/docker-enter
-
function docker-enter() {
-
#if [ -e $(dirname "$0")/nsenter ]; then
-
#Change for centos bash running
-
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
-
# if nsenter has already been installed with path notified, here will be clarified
-
NSENTER=$(which nsenter)
-
#NSENTER=nsenter
-
fi
-
[ -z "$NSENTER" ] && echo "WARN Cannot find nsenter" && return
-
-
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=$(sudo docker inspect --format "{{.State.Pid}}" "$1")
-
if [ -z "$PID" ]; then
-
echo "WARN Cannot find the given container"
-
return
-
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.
-
#sudo $NSENTER "$OPTS" su - root
-
sudo $NSENTER --target $PID --mount --uts --ipc --net --pid su - root
-
else
-
# Use env to clear all host environment variables.
-
sudo $NSENTER --target $PID --mount --uts --ipc --net --pid env -i $@
-
fi
-
fi
-
}
阅读(1058) | 评论(0) | 转发(0) |