This page looks best with JavaScript enabled

How to Make a Port Accessible Only to a Specified IP

1. Host Service Ports

1
2
iptables -I INPUT -p tcp --dport 80 -j DROP
iptables -I INPUT -p tcp -s 1.2.3.4 --dport 80 -j ACCEPT

This allows only 1.2.3.4 to access port 80 on the local host.

2. Docker Service Ports

For services started like docker run -d -p 80:80 shaowenchen/demo:whoami, the method above does not work; the rule has to be added to the DOCKER-USER chain.

Docker adds its iptables rules to the DOCKER chain, so if you need a rule to take effect before Docker’s, it has to go into the DOCKER-USER chain.

1
iptables -I DOCKER-USER -i ens192 ! -s 1.2.3.4 -p tcp --dport 80 -j DROP

ens192 is the local NIC. This allows only 1.2.3.4 to access port 80 on the local host.

3. Clean Up the Environment

1
2
yum install -y iptables-services
systemctl restart iptables.service

If you want the iptables settings to remain in effect after the host restarts, you need to install iptables-services and save them.

1
2
yum install -y iptables-services
service iptables save

4. References


WeChat Official Account
WRITTEN BY
WeChat Official Account