我想将对 docker 容器的访问限制为仅几个 ip 地址。服务器上有两个接口:公共 (eth0) 和私有 (eth1:192.168.0.1)。我只希望私有接口上的 IP 能够访问容器,因此我阻止了来自公共接口的所有流量。我尝试添加一条规则来授权特定 IP 访问容器,但这不起作用。我的 iptables 如下所示:
sudo iptables -vL DOCKER-USER
Chain DOCKER-USER (1 references)
pkts bytes target prot opt in out source destination
0 0 ACCEPT tcp -- eth1 any 192.168.0.2 192.168.0.1 tcp dpt:XXXX
0 0 ACCEPT all -- eth1 any 192.168.0.1 192.168.0.2 ctstate RELATED,ESTABLISHED
0 0 ACCEPT all -- eth1 any anywhere anywhere ctstate RELATED,ESTABLISHED
38824 2328K DROP all -- eth1 any anywhere anywhere
14596 678K ACCEPT all -- eth0 any anywhere anywhere ctstate RELATED,ESTABLISHED
12337 657K DROP all -- eth0 any anywhere anywhere
770K 1335M RETURN all -- any any anywhere anywhere
我无法从 IP 192.168.0.2 访问端口 XXXX,该端口在主机上暴露如下:
0.0.0.0:XXXX->YYYY/tcp
答案1
I:问题是 Docker 容器使用与主机相同的接口。要解决此问题,您需要创建一个自定义网络并将容器连接到此网络。
创建自定义网络
docker network create --driver=bridge --subnet=192.168.0.0/24 --gateway=192.168.0.1 my-network
将容器连接到新网络
docker run --net=my-network --ip=192.168.0.2 ...
配置 iptables
sudo iptables -vL DOCKER-USER
Chain DOCKER-USER (1 references)
pkts bytes target prot opt in out source destination
0 0 ACCEPT tcp -- eth1 any 192.168.0.2 192.168.0.1 tcp dpt:XXXX
0 0 ACCEPT all -- eth1 any 192.168.0.1 192.168.0.2 ctstate RELATED,ESTABLISHED
0 0 ACCEPT all -- eth1 any anywhere anywhere ctstate RELATED,ESTABLISHED
38824 2328K DROP all -- eth1 any anywhere anywhere
14596 678K ACCEPT all -- eth0 any anywhere anywhere ctstate RELATED,ESTABLISHED
12337 657K DROP all -- eth0 any anywhere anywhere
770K 1335M RETURN all -- any any anywhere anywhere
现在您可以从 IP 192.168.0.2 访问该容器。
II:您可以使用 iptables 创建自定义桥接网络。如果您已连接其他机器上的容器,并且只想允许特定 IP 范围访问这些容器,这将非常有用。如果您使用以下命令:
sudo iptables -N DOCKER
然后您可以添加以下规则:
sudo iptables -A FORWARD -o docker0 -j DOCKER
sudo iptables -A FORWARD -o docker0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A FORWARD -i docker0 ! -o docker0 -j ACCEPT
sudo iptables -A FORWARD -o docker0 -j DROP
这将允许容器相互通信。然后,您可以使用以下命令添加允许从特定 IP 范围访问容器的规则:
sudo iptables -A DOCKER -s [your ip range] -j ACCEPT
答案2
我按照以下方法做了我想做的事这。事实证明,您需要在内部容器端口而不是主机上添加 iptables 规则。我还删除了目标 IP 192.168.0.1。以下是最终的 iptables 规则:
Chain DOCKER-USER (1 references)
pkts bytes target prot opt in out source destination
0 0 ACCEPT tcp -- eth1 any 192.168.0.2 anywhere tcp dpt:YYYY
0 0 ACCEPT all -- eth1 any anywhere anywhere ctstate RELATED,ESTABLISHED
0 0 DROP all -- eth1 any anywhere anywhere
0 0 ACCEPT all -- eth0 any anywhere anywhere ctstate RELATED,ESTABLISHED
0 0 DROP all -- eth0 any anywhere anywhere
0 0 RETURN all -- any any anywhere anywhere
编辑:如果目标 IP 设置为 Docker IP 范围,规则仍然有效