使用nsenter进入docker container

2016年12月27日

1 安装 nsenter

  1. apt-get install util-linux

2 使用 nsenter

  1. cat /home/shell/docker-enter
  1. #!/bin/sh
  2. if [ -e $(dirname "$0")/nsenter ]; then
  3. # with boot2docker, nsenter is not in the PATH but it is in the same folder
  4. NSENTER=$(dirname "$0")/nsenter
  5. else
  6. NSENTER=nsenter
  7. fi
  8. if [ -z "$1" ]; then
  9. echo "Usage: `basename "$0"` CONTAINER [COMMAND [ARG]...]"
  10. echo ""
  11. echo "Enters the Docker CONTAINER and executes the specified COMMAND."
  12. echo "If COMMAND is not specified, runs an interactive shell in CONTAINER."
  13. else
  14. PID=$(docker inspect --format "{{.State.Pid}}" "$1")
  15. if [ -z "$PID" ]; then
  16. exit 1
  17. fi
  18. shift
  19. OPTS="--target $PID --mount --uts --ipc --net --pid --"
  20. if [ -z "$1" ]; then
  21. # No command given.
  22. # Use su to clear all host environment variables except for TERM,
  23. # initialize the environment variables HOME, SHELL, USER, LOGNAME, PATH,
  24. # and start a login shell.
  25. "$NSENTER" $OPTS su - root
  26. else
  27. # Use env to clear all host environment variables.
  28. "$NSENTER" $OPTS env --ignore-environment -- "$@"
  29. fi
  30. fi

保存后,执行:
docker ps -a #获取docker的container的pid或者name
[root@debian8-test ~]# docker ps -a

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b281316df403 percona/pmm-server "/opt/entrypoint.sh" 16 hours ago Up 16 hours 0.0.0.0:2233->22/tcp, 0.0.0.0:8077->80/tcp, 0.0.0.0:8443->443/tcp pmm-server
5af9de62d711 percona/pmm-server "/bin/true" 16 hours ago Created pmm-data

使用方法:

  1. sh /home/shell/docker-enter (CONTAINER ID) or (NAMES)
  2. OR
  3. chown +x /home/shell/docker-enter
  4. /home/shell/docker-enter (CONTAINER ID) or (NAMES)

示例:

  1. /home/shell/docker-enter b281316df403
  2. OR
  3. /home/shell/docker-enter pmm-server

退出 exit 即可;

没有评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注