Thursday, November 21, 2024
HomeDockerHow does Docker Port Binding Works

How does Docker Port Binding Works

In Real time, Docker containers have connects to the outside world without further configuration, but the outside world cannot connect to Docker containers by default.

How it works

A bridge network is created (with the name bridge) when you install Docker. Every outgoing connection appears to originate from the host’s IP space; Docker creates a custom iptables masquerading rule. To check the rules use;

# 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
MASQUERADE  all  --  172.18.0.0/16        0.0.0.0/0
MASQUERADE  all  --  10.137.0.0/16        0.0.0.0/0
MASQUERADE  all  --  172.17.0.0/16        0.0.0.0/0

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
RETURN     all  --  0.0.0.0/0            0.0.0.0/0

Forward everything

If you append -P (or –publish-all=true) to docker run, Docker identifies every port the Dockerfile exposes (you can see which ones by looking at the EXPOSE lines). Docker also finds ports you expose with –expose 8080 (assuming you want to expose port 8080). Docker maps all of these ports to a host port within a given epehmeral port range. You can find the configuration for these ports (usually 32768 to 61000) in /proc/sys/net/ipv4/ip_local_port_range.

How to Check

We can use the docker port command to inspect the mapping Docker creates.

Forward selectively

You can also specify ports. When doing so, you don’t need to use ports from the ephemeral port range. Suppose you want to expose the container’s port 8080 (standard http port) on the host’s port 8081 (assuming that port is not in use). Append -p 8081:8080 (or –publish=8081:8080) to your docker run command. For example:

# docker run -p 8081:8080 nginx
## OR ##
# docker run --publish=8081:8080 nginx

Custom IP and port forwarding

By default, Docker exposes container ports to the IP address 0.0.0.0 (this matches any IP on the system). If you prefer, you can tell Docker which IP to bind on. To bind on IP address 10.0.0.3, host port 8081, and container port 8080:

# docker run -p 192.168.0.161:8081:8080 nginx
RELATED ARTICLES
- Advertisment -

Most Popular

Recent Comments