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.

Liangxu Linux
Liangxu Linux
Liangxu Linux
Restrict Host and Docker Ports to a Specific IP Using iptables

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 ACCEPT

The 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 DROP

Here 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.service

After making changes, save the rules so they are re‑loaded on boot.

$ yum install -y iptables-services
$ service iptables save

Reference

https://docs.docker.com/network/iptables/

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

DockerfirewallLinuxnetwork securityiptables
Liangxu Linux
Written by

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.)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.