注意 nsenter 需要配合 EOF 完成标准输入,范式如下:
nsenter -t $pid -n bash <<EOF
something run in container namespace
exit
EOF
例如,给容器批量设置 iptables 规则的写法,如下:
for id in $(docker ps | grep k8s_POD | awk '{print $1}')
do
pid=$(docker inspect $id -f '{{.State.Pid}}')
nsenter -t $pid -n bash <<EOF
if ! iptables -t nat -S | grep OUTPUT | grep 192.168.0.1; then
iptables -t nat -I OUTPUT -p all -d 1.2.3.4 -j DNAT --to-destination 192.168.0.1
iptables -t nat -I OUTPUT -d 10.96.0.1 -p tcp --dport 443 -j DNAT --to-destination 192.168.0.1:6443
fi
exit
EOF
done

这篇博客介绍了如何利用nsenter工具进入Docker容器的命名空间,并通过bash脚本批量设置iptables规则。具体步骤包括获取容器PID,然后使用nsenter命令进入容器并检查及添加iptables规则,确保特定的流量被正确地DNAT。
1186

被折叠的 条评论
为什么被折叠?



