我正在构建一个库来模拟系统中的一些故障。其中一个缺点是模拟网络故障,这将禁止任何连接。目前,我正在使用这个Kotlin代码来禁用容器网络接口:
Runtime.getRuntime().exec("ifconfig eth0 down")
// wait some time
Runtime.getRuntime().exec("ifconfig eth0 up")当接口重新启用时,我无法恢复与容器的连接。我在命令行中尝试了一下,效果是一样的:
docker run --privileged -it alpine:latest sh
/ # apk add curl
...
OK: 7 MiB in 18 packages
/ # curl google.com
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
/ # ifconfig eth0 down
/ # ifconfig eth0 up
/ # curl google.com
curl: (6) Could not resolve host: google.com有没有人知道为什么它会出现在码头容器中?
发布于 2019-12-31 06:18:34
Docker设置了许多东西来将网络转发到主机,包括iptables、网桥网络、ipvs和路由。我怀疑删除eth0接口至少破坏了其中一个组件的配置。要恢复,您可能需要重新启动docker引擎(systemctl restart docker)。
我建议使用tc来丢弃所有数据包,而不是丢弃接口。甚至有一个项目可以通过单个容器上的标签来实现这一点,或者由一个应用程序接口控制,你可以在lukaszlach/docker-tc上找到它。
发布于 2020-01-01 02:51:54
问题是Docker正在丢失默认网关地址。我刚刚添加了另一个命令,在重启接口后重置网关地址,一切都正常了:
route add default gw ${this.defaultGatewayAddress}最后,我得到了以下可用的Kotlin代码:
data class NetworkInterface(val name: String) {
private var defaultGatewayAddress: String
init {
this.defaultGatewayAddress = getDefaultGatewayIpAddress().address
}
fun disable() {
Environment.runCLICommand("ifconfig $name down")
}
fun enable() {
Environment.runCLICommand("ifconfig $name down")
Environment.runCLICommand("route add default gw ${this.defaultGatewayAddress}")
}
fun getDefaultGatewayIpAddress(): IpAddress {
val command = "netstat -nr | awk '{print $2}' | head -n3 | tail -n1"
return IpAddress(Environment.runCLICommand(command).trim())
}
}https://stackoverflow.com/questions/59537341
复制相似问题