In Linux systems, blocking specific ports can be achieved through various methods, primarily by using firewall rules or directly stopping the service running on that port. Below, I will explain the specific steps and examples for both methods.
Method One: Using Firewall Rules
Using iptables
-
View existing iptables rules:
bashsudo iptables -L -
Add a rule to block incoming connections to the specific port (e.g., block port 8080):
bashsudo iptables -A INPUT -p tcp --dport 8080 -j DROP -
Save and reload iptables rules (commands may vary across different Linux distributions):
bashsudo iptables-saveOr, in some systems, you may need to use:
bashsudo netfilter-persistent save sudo netfilter-persistent reload
Using firewalld (on systems supporting firewalld)
-
Check the current firewalld status:
bashsudo firewall-cmd --state -
Permanently block the specific port (e.g., block port 8080):
bashsudo firewall-cmd --permanent --remove-port=8080/tcp -
Reload the firewalld configuration:
bashsudo firewall-cmd --reload
Method Two: Stopping the Service Running on the Port
-
First, identify which service is using the port:
bashsudo lsof -i :8080 -
Stop the related service (e.g., nginx):
bashsudo systemctl stop nginx -
Disable the service from starting automatically:
bashsudo systemctl disable nginx
By following these steps, you can effectively block specific ports on Linux, whether by directly managing the firewall or by managing the related services. Each method has its applicable scenarios, and choosing the right method depends on actual requirements and system environment.