Home  >  Article  >  System Tutorial  >  How to restrict port access to only specified IPs in Linux

How to restrict port access to only specified IPs in Linux

WBOY
WBOYforward
2024-02-09 17:54:11654browse

This article focuses on explaining the specific method of restricting port access to only specified IPs under Linux. Friends in need can refer to it.

如何在 Linux 下限制端口仅对指定 IP 开放访问

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

Only 1.2.3.4 is allowed to access port 80 of the local host.

Docker service port

For services running like docker run -d -p 80:80 shaowenchen/demo-whoami, the above method is invalid and you need to add rules in the DOCKER-USER chain.

Docker will add iptables rules to the DOCKER chain. If you need to add rules before Docker, you need to add them to the DOCKER-USER chain

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

ens192 is the local network card. Only 1.2.3.4 is allowed to access port 80 of the local host.

Clean up the environment

$ yum install -y iptables-services
$ systemctl restart iptables.service

If you need the iptables settings to remain valid after the host is restarted, you need to install iptables-services and save

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

The above is the detailed content of How to restrict port access to only specified IPs in Linux. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:lxlinux.net. If there is any infringement, please contact admin@php.cn delete