Docker 2.5:使用 nsenter 命令进入 Docker 容器

2.5:nsenter 命令

nsenter 命令可以通过容器在宿主机上的 PID 进入到容器内部;

2.5.1:nsenter 命令帮助

root@ubuntu:~# nsenter -h

Usage:
 nsenter [options] [<program> [<argument>...]]

Run a program with namespaces of other processes.

Options:
 -a, --all              enter all namespaces
 -t, --target <pid>     target process to get namespaces from
 -m, --mount[=<file>]   enter mount namespace
 -u, --uts[=<file>]     enter UTS namespace (hostname etc)
 -i, --ipc[=<file>]     enter System V IPC namespace
 -n, --net[=<file>]     enter network namespace
 -p, --pid[=<file>]     enter pid namespace
 -C, --cgroup[=<file>]  enter cgroup namespace
 -U, --user[=<file>]    enter user namespace
 -S, --setuid <uid>     set uid in entered namespace
 -G, --setgid <gid>     set gid in entered namespace
     --preserve-credentials do not touch uids or gids
 -r, --root[=<dir>]     set the root directory
 -w, --wd[=<dir>]       set the working directory
 -F, --no-fork          do not fork before exec'ing <program>
 -Z, --follow-context   set SELinux context according to --target PID

 -h, --help             display this help
 -V, --version          display version

2.5.2:nsenter 通过容器 PID 进入容器

直接使用 -a 选项进入所有 namespaces:

CentOS 7.2 的 nsenter 版本为 2.23.2,尚不支持 -a 选项;
Ubuntu 18.04 的 nsenter-2.31.1 已支持;

root@ubuntu:~# nsenter -t 3089 -a
mesg: ttyname failed: No such device
root@d6055a62a90b:/#

或者指定各 namespace:

root@ubuntu:~# nsenter -t 3089 -m -u -i -n -p
mesg: ttyname failed: No such device
root@d6055a62a90b:/# 

2.5.3:进入容器的脚本

通过脚本后面指定容器,获取容器 PID,并调用 nsenter 进入容器;

编写脚本:

root@ubuntu:~# vim enter_docker.sh
#!/bin/bash
enter_docker(){
	Docker=$1
	Pid=$(docker inspect -f "{{.State.Pid}}" ${Docker})
	nsenter -t ${Pid} -a
}
enter_docker $1

赋予脚本执行权限:

root@ubuntu:~# chmod +x enter_docker.sh 

测试脚本:

root@ubuntu:~# docker run -itd --name centos-test centos    
e5d3dfafe8f818bbae47ae22ac8e6a2bc65748b61ac68fb49ddeb538665ead89

root@ubuntu:~# ./enter_docker.sh centos-test
[root@e5d3dfafe8f8 /]# cat /etc/redhat-release 
CentOS Linux release 8.3.2011
[root@e5d3dfafe8f8 /]# exit
logout
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值