What is the best practice of docker + ufw under Ubuntu

后端 未结 8 1361
旧巷少年郎
旧巷少年郎 2020-11-27 10:14

I just tried out Docker. It is awesome but seems not work nicely with ufw. By default, docker will manipulate the iptables a little bit. The outcome is not a bug but not wha

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 11:01

    For what it's worth here's an addendum to @mkubaczyk's answer for the case where there are more bridge networks involved in the whole setup. These may be provided by Docker-Compose projects and here's how the proper rules can be generated, given that these projects are controlled by systemd.

    /etc/systemd/system/compose-project@.service

    [Unit]
    Description=Docker-Compose project: %I
    After=docker.service
    BindsTo=docker.service
    AssertPathIsDirectory=//%I
    AssertFileNotEmpty=//%I/docker-compose.yml
    
    [Service]
    Type=simple
    Restart=always
    WorkingDirectory=//%I
    ExecStartPre=/usr/bin/docker-compose up --no-start --remove-orphans
    ExecStartPre=+/usr/local/bin/update-iptables-for-docker-bridges
    ExecStart=/usr/bin/docker-compose up
    ExecStop=/usr/bin/docker-compose stop --timeout 30
    TimeoutStopSec=30
    User=<…>
    StandardOutput=null
    
    [Install]
    WantedBy=multi-user.target
    

    /usr/local/bin/update-iptables-for-docker-bridges

    #!/bin/sh
    
    for network in $(docker network ls --filter 'driver=bridge' --quiet); do
      iface=$(docker network inspect --format '{{index .Options "com.docker.network.bridge.name"}}' ${network})
      [ -z $iface ] && iface="br-${network}"
      subnet=$(docker network inspect --format '{{range .IPAM.Config}}{{.Subnet}}{{end}}' ${network})
      rule="! --out-interface ${iface} --source ${subnet} --jump MASQUERADE"
      iptables --table nat --check POSTROUTING ${rule} || iptables --table nat --append POSTROUTING ${rule}
    done
    

    Obviously, this won't scale that well.

    It's also noteworthy that the whole basic concept will disguise the source of any connection for the applications running in a container.

提交回复
热议问题