1

我正在清除 /etc/resolv.conf 以禁用网络:

sudo mv /etc/resolv.conf /etc/resolv_backup.conf
sudo touch /etc/resolv.conf

然后启用网络:

sudo mv /etc/resolv_backup.conf /etc/resolv.conf

但是资源很忙,我无法执行这些命令。

我想从容器内禁用互联网,而不是使用:

docker network disconnect [选项] 网络容器

从部署容器的服务器执行此操作。我正在使用阿尔卑斯山。

4

2 回答 2

3

从容器内部,您通常被禁止更改网络状态:

$ docker run -it --rm alpine:latest /bin/sh
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
929: eth0@if930: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue state UP
    link/ether 02:42:ac:11:00:03 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.3/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
/ # ip link set eth0 down
ip: ioctl 0x8914 failed: Operation not permitted

为了安全起见,这是故意的,以防止应用程序逃离容器沙箱。如果您不需要容器的安全性(因此我建议不要这样做),您可以使用额外的网络功能运行您的容器:

$ docker run -it --rm --cap-add NET_ADMIN alpine:latest /bin/sh
/ # netstat -nr
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
0.0.0.0         172.17.0.1      0.0.0.0         UG        0 0          0 eth0
172.17.0.0      0.0.0.0         255.255.0.0     U         0 0          0 eth0
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
933: eth0@if934: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue state UP
    link/ether 02:42:ac:11:00:03 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.3/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
/ # ip link set eth0 down
/ # ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8): 56 data bytes
ping: sendto: Network unreachable

当您尝试恢复网络时,您还需要再次设置默认路由才能连接到外部网络:

/ # ip link set eth0 up
/ # ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8): 56 data bytes
ping: sendto: Network unreachable
/ # netstat -nr
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
172.17.0.0      0.0.0.0         255.255.0.0     U         0 0          0 eth0
/ # route add default gw 172.17.0.1
/ # ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8): 56 data bytes
64 bytes from 8.8.8.8: seq=0 ttl=58 time=12.518 ms
64 bytes from 8.8.8.8: seq=1 ttl=58 time=11.481 ms
^C
--- 8.8.8.8 ping statistics ---
2 packets transmitted, 2 packets received, 0% packet loss
round-trip min/avg/max = 11.481/11.999/12.518 ms
于 2018-06-18T12:46:51.457 回答
0

首先,清除 resolv.conf 不是为您的容器禁用网络的正确方法。这只是避免了名称解析,但您仍然可以使用 IP 连接。

要禁用网络,您应该使用正确的脚本,具体取决于您使用的是 systemd 还是 sysV。与此类似的东西应该可以工作(这取决于您的发行版):

# /etc/init.d/networking stop
# systemctl stop networking

希望这可以帮助!:-)

于 2018-06-18T10:17:31.013 回答