docker 使用 iptables 进行网络通信

docker 是虽然是一个容器,但是也是一个小型的系统,它也有自己的网络, 因此 docker 和 宿主机之间网络通信也是要配置的,你有以下方式

  • 通过 --net=host 直接共用宿主机网络
  • 通过 -p 宿主机端口:容器端口 进行指定,而这种方式需要用 iptables 进行转换

如何利用 iptables 进行转发呢?

  • 配置 SELINUX=disabled

    如下所示

    vi /etc/selinux/config
    
    # This file controls the state of SELinux on the system.
    # SELINUX= can take one of these three values:
    #     enforcing - SELinux security policy is enforced.
    #     permissive - SELinux prints warnings instead of enforcing.
    #     disabled - No SELinux policy is loaded.
    SELINUX=disabled
    # SELINUXTYPE= can take one of these two values:
    #     targeted - Targeted processes are protected,
    #     mls - Multi Level Security protection.
    SELINUXTYPE=targeted
    
  • 开启系统转换

    vi /etc/sysctl.conf
    
    net.ipv4.ip_forward = 1
    
  • 配置 iptables

    *nat
    :PREROUTING ACCEPT [27:11935]
    :OUTPUT ACCEPT [598:57368]
    :POSTROUTING ACCEPT [591:57092]
    :DOCKER - [0:0]
    -A PREROUTING -m addrtype --dst-type LOCAL -j DOCKER
    -A OUTPUT ! -d 127.0.0.0/8 -m addrtype --dst-type LOCAL -j DOCKER
    -A POSTROUTING -s 172.17.0.0/16 ! -o docker0 -j MASQUERADE
    -A POSTROUTING -j MASQUERADE
    
    COMMIT
    # Completed on Sun Sep 20 17:35:31 2015
    # Generated by iptables-save v1.4.21 on Sun Sep 20 17:35:31 2015
    *filter
    :INPUT ACCEPT [0:0]
    #:INPUT DROP [0:0]
    :FORWARD ACCEPT [0:0]
    :OUTPUT ACCEPT [127386:5251162]
    
    :DOCKER - [0:0]
    
    -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
    -A INPUT -s 192.168.1.0/24 -j ACCEPT
    -A INPUT -s 172.17.0.0/16 -j ACCEPT
    -A INPUT -s 127.0.0.0/8 -j ACCEPT
    
    -A INPUT -i lo -p all -j ACCEPT
    -A OUTPUT -o lo -p all -j ACCEPT
    
    -A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
    
    -A FORWARD -o docker0 -j DOCKER
    -A FORWARD -o docker0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
    -A FORWARD -i docker0 ! -o docker0 -j ACCEPT
    -A FORWARD -i docker0 -o docker0 -j ACCEPT
    -A FORWARD -s 192.168.1.0/24 -j ACCEPT
    -A FORWARD -d 192.168.1.0/24 -j ACCEPT
    
    -A FORWARD -s 172.17.0.0/16 -j ACCEPT
    -A FORWARD -d 172.17.0.0/16 -j ACCEPT
    
    COMMIT
    

最后重启 Centos 系统

reboot