Restrict Host and Docker Ports to a Specific IP Using iptables
This guide shows how to use iptables to allow only a designated IP address to access a host's port 80, how to apply the same restriction to Docker containers by adding rules to the DOCKER-USER chain, and how to make the settings persistent across reboots.
Host Service Port
$ iptables -I INPUT -p tcp --dport 80 -j DROP
$ iptables -I INPUT -p tcp -s 1.2.3.4 --dport 80 -j ACCEPTThe first rule drops all incoming TCP traffic to port 80. The second rule inserts an exception that permits only the IP address 1.2.3.4 to reach the local host on port 80.
Docker Service Port
When a container is started with a command such as docker run -d -p 80:80 shaowenchen/demo-whoami, the previous host‑level rules do not apply because Docker inserts its own iptables chains. To filter traffic before Docker processes it, add a rule to the DOCKER-USER chain.
$ iptables -I DOCKER-USER -i ens192 ! -s 1.2.3.4 -p tcp --dport 80 -j DROPHere ens192 is the local network interface. This rule drops any TCP traffic to port 80 that does not originate from 1.2.3.4, effectively restricting access to the Docker‑exposed service.
Cleaning Environment
To ensure the iptables configuration remains after a system reboot, install the iptables‑services package and restart the service.
$ yum install -y iptables-services
$ systemctl restart iptables.serviceAfter making changes, save the rules so they are re‑loaded on boot.
$ yum install -y iptables-services
$ service iptables saveReference
https://docs.docker.com/network/iptables/
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
