如何通过特定网络接口路由来自子网出站的流量?

时间:2017-09-15 06:51:40

标签: iptables

我正在研究这个问题: how to assign specific network interface to docker container

现在我正在使用此页面中的子网和iptable解决方案: https://github.com/moby/moby/issues/30053

docker network create NETWORK --subnet=192.168.1.0/24 --gateway=192.168.1.1 # choose an unused subnet
iptables -t nat -I POSTROUTING -s 192.168.1.0/24 -j SNAT --to-source OUTGOING_IP # remember that Docker also edit POSTROUTING
docker network connect NETWORK CONTAINER # or with Compose

我不熟悉网络。我只是跑

docker network create mynetwork

Docker为我处理子网的事情。我检查了它的信息

[
{
    "Name": "mynetwork",
    "Id": "b61fc94a84f43c186d208d7406f6a3869cae3f6e4a5ed6cd01e6df30ed926a68",
    "Created": "2017-09-15T06:29:36.582492084Z",
    "Scope": "local",
    "Driver": "bridge",
    "EnableIPv6": false,
    "IPAM": {
        "Driver": "default",
        "Options": {},
        "Config": [
            {
                "Subnet": "172.18.0.0/16",
                "Gateway": "172.18.0.1"
            }
        ]
    },
    "Internal": false,
    "Attachable": false,
    "Ingress": false,
    "ConfigFrom": {
        "Network": ""
    },
    "ConfigOnly": false,
    "Containers": {},
    "Options": {},
    "Labels": {}
}

按照这些步骤,我在主机上运行它 (1.2.3.4是eth1的IP,我希望来自docker容器的流量通过它出站)

iptables -t nat -I POSTROUTING -s 172.18.0.0/16 -j SNAT --to-source 1.2.3.4

检查iptables

    iptables -t nat -L -n
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination         
DOCKER     all  --  0.0.0.0/0            0.0.0.0/0            ADDRTYPE match dst-type LOCAL

Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         
DOCKER     all  --  0.0.0.0/0           !127.0.0.0/8          ADDRTYPE match dst-type LOCAL

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination         
SNAT       all  --  172.18.0.0/16        0.0.0.0/0            to:1.2.3.4
MASQUERADE  all  --  172.18.0.0/16        0.0.0.0/0           
MASQUERADE  all  --  172.17.0.0/16        0.0.0.0/0           
MASQUERADE  tcp  --  172.17.0.2           172.17.0.2           tcp dpt:3306
MASQUERADE  tcp  --  172.17.0.3           172.17.0.3           tcp dpt:443
MASQUERADE  tcp  --  172.17.0.3           172.17.0.3           tcp dpt:80

Chain DOCKER (2 references)
target     prot opt source               destination         
RETURN     all  --  0.0.0.0/0            0.0.0.0/0           
RETURN     all  --  0.0.0.0/0            0.0.0.0/0           
DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:3306 to:172.17.0.2:3306
DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:443 to:172.17.0.3:443
DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:80 to:172.17.0.3:80

运行“curl ifconfig.co”,我仍然获得eth0的IP而不是eth1。 我错过了什么吗?

我想创建一些子网,每个子网中只有一个用户。如果我愿意,我应该在“--subnet”参数中指定什么?

感谢。

0 个答案:

没有答案