Docker Community Forums

Share and learn in the Docker community.

Connecting from host to container


(Rogier Lommers) #1

My server has two NICs, p1p1 (internal network) and eth0 (connected to modem). The server acts as a router for the internal network. I use the below set of iptables rules and for some reason, I need to add iptables -A INPUT -i docker0 -p all -j ACCEPT and iptables -A OUTPUT -o docker0 -p all -j ACCEPT before the host can reach the docker ontainers. Why is that? Why do I need to add those rules? I thought the docker run command was adding these rules on the fly, right?

A simple example to illustrate my problem: when I run ``

[server][~/scripts] sudo docker run -d -p 80 tutum/hello-world
2c5a2e9b333a1bf7e63cce018b89aa1c111baa891b12cb32ddc2e7deb1ba1ea5
[server][~/scripts] docker ps
CONTAINER ID        IMAGE                      COMMAND             CREATED             STATUS              PORTS                   NAMES
2c5a2e9b333a        tutum/hello-world:latest   "/run.sh"           3 seconds ago       Up 3 seconds        0.0.0.0:49153->80/tcp   elegant_lovelace

Now when I try to curl localhost:49153, I get a timeout. Only after adding the above mentioned two iptable rules, I’m able to connect the container from the host.

My set of iptable rules

#!/bin/sh
# p1p1 = internal NIC
# eth0 = WAN NIC
lan_nic=p1p1
wan_nic=eth0

echo "Clear old firewall rules..."
iptables --flush
iptables --flush FORWARD
iptables --flush INPUT
iptables --flush OUTPUT
iptables --table nat --flush
iptables --table nat --delete-chain
iptables --table mangle --flush
iptables --table mangle --delete-chain
iptables --delete-chain

echo "Drop all INPUT and FORWARD..."
iptables -P INPUT DROP
iptables -P FORWARD DROP

echo "Drop all IPv6 traffic..."
ip6tables -P INPUT DROP
ip6tables -P OUTPUT DROP
ip6tables -P FORWARD DROP

echo "Accept everything on lo and $lan_nic (local network)..."
iptables -A INPUT -i lo -p all -j ACCEPT
iptables -A OUTPUT -o lo -p all -j ACCEPT

iptables -A INPUT -i docker0 -p all -j ACCEPT
iptables -A OUTPUT -o docker0 -p all -j ACCEPT

iptables -A INPUT -i $lan_nic -p all -j ACCEPT -s 192.168.1.0/24
iptables -A OUTPUT -o $lan_nic -p all -j ACCEPT -d 192.168.1.0/24

echo "IP Forwarding and Routing for gateway use..."
iptables -A FORWARD -o $wan_nic -i $lan_nic -s 192.168.1.0/24 -m conntrack --ctstate NEW -j ACCEPT
iptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -t nat -A POSTROUTING -o $wan_nic -j MASQUERADE

echo "Maintain established connections..."
iptables -A INPUT --in-interface $wan_nic --match conntrack --ctstate ESTABLISHED,RELATED --jump ACCEPT

echo "Logging all dropped packets"
iptables -N LOGGING
iptables -A INPUT -j LOGGING
iptables -A LOGGING -m limit --limit 2/min -j LOG --log-prefix "IPTables-Dropped: " --log-level 4
iptables -A LOGGING -j DROP