我有一种情况可以限制负载均衡器网络中容器的Internet访问。例如下面的图片
仅container4连接到Internet;其他three仅通过container4与外界通信。例如,如果container1需要smtp支持,它将把smtp请求转发到container4以获得访问权限。
除container4之外的任何容器都不允许直接访问互联网!这应该在Docker级别上强制执行。
我相信它可以在docker网络创建上进行配置,任何人都可以解释如何实现吗?
[发现here,我将其与docker-compose一起使用。另存为docker-compose.yml
:
version: '3'
services:
outgoing-wont-work:
image: alpine
networks:
- no-internet
command: ping -c 3 google.com # will crash
internal-will-work:
image: alpine
networks:
- no-internet
command: ping -c 3 internal-and-external
internal-and-external:
image: alpine
networks:
- no-internet
- internet
command: ping -c 3 google.com
networks:
no-internet:
driver: bridge
internal: true
internet:
driver: bridge
然后运行docker-compose up -d
,docker-compose ps
将在几秒钟后显示如下内容:
Name Command State Ports
----------------------------------------------------------------------------------
dco_inet_internal-and-external_1 ping -c 3 google.com Exit 0
dco_inet_internal-will-work_1 ping -c 3 internal-and-ext ... Exit 0
dco_inet_outgoing-wont-work_1 ping -c 3 google.com Exit 1
用于访问互联网的网络创建
docker网络创建--subnet = 172.19.0.0 / 16互联网
用于阻止Internet访问的网络创建
docker网络创建-内部-子网10.1.1.0/24无互联网
如果您想将Docker容器连接到互联网上
docker network connect internet container-name
如果您想阻止互联网访问
docker network connect no-internet container-name
在内部网络中,我们无法暴露用于连接外部世界的端口,请参考此question以获取更多详细信息
[另一种选择,如果您需要在没有Internet访问的情况下暴露容器上的端口,但是要让它与其他容器进行通信,那就是提供伪造的DNS配置。但是,这并不是一个完美的解决方案,因为它不会阻止直接IP访问外界。
docker-compose.yaml
version: '3'
services:
service1:
image: alpine
command: sh -c 'ping service2 -c 1; ping google.com -c 1'
dns: 0.0.0.0
service2:
image: alpine
command: sh -c 'ping service1 -c 1; ping google.com -c 1'
dns: 0.0.0.0
isolated> docker-compose up
Recreating isolated_service1_1 ... done Recreating isolated_service2_1 ... done Attaching to isolated_service2_1, isolated_service1_1
service1_1 | PING service2 (172.18.0.2) 56(84) bytes of data.
service1_1 | 64 bytes from isolated_service2_1.isolated_default (172.18.0.2): icmp_seq=1 ttl=64 time=0.038 ms
service1_1 |
service1_1 | --- service2 ping statistics ---
service1_1 | 1 packets transmitted, 1 received, 0% packet loss, time 0ms
service1_1 | rtt min/avg/max/mdev = 0.038/0.038/0.038/0.000 ms
service2_1 | PING service1 (172.18.0.3) 56(84) bytes of data.
service2_1 | 64 bytes from isolated_service1_1.isolated_default (172.18.0.3): icmp_seq=1 ttl=64 time=0.093 ms
service2_1 |
service2_1 | --- service1 ping statistics ---
service2_1 | 1 packets transmitted, 1 received, 0% packet loss, time 0ms
service2_1 | rtt min/avg/max/mdev = 0.093/0.093/0.093/0.000 ms
service1_1 | ping: google.com: Temporary failure in name resolution
service2_1 | ping: google.com: Temporary failure in name resolution
isolated_service1_1 exited with code 2
isolated_service2_1 exited with code 2