Open and Close Ports using IPTables
IPtables is the default firewall used on CentOS and RHEL systems. On most of First2Host services like VPS Servers or Dedicated Servers, you will find the firewall is active but all ports are open. We do this to ensure all users can connect to services they may install like cPanel or Plesk. If you want to close some ports on your server or even open some if you have a pre-configured firewall you can use the rules below to open and close ports on your firewall.
List Current Firewall Rules
This command lists all the current firewall rules loaded into IPtables.
Open a port in IPtables – CentOS 6
iptables -I INPUT -p tcp -m tcp --dport 80 -j ACCEPT service iptables save
Open a port in IPtables – CentOS 7
firewall-cmd --zone=public --add-port=80/tcp --permanent firewall-cmd --reload
In CentOS 7 you use the –permanent flag to open the port. Like in CentOS 6 just swap the number 80 for your required port and run the –reload command
This command opens the requested port. In our example, it’s port 80. Just swap the 80 for the port number you wish to open. Run the service iptables save command to save the rules to your firewall configuration.
Close a port in IPtables – CentOS 6
iptables -I INPUT -p tcp -m tcp --dport 80 -j REJECT service iptables save
This command would close the port 80 on your server and no one would be able to connect via that port. Just swap the 80 for your required port number then run the service iptables save command to save this to your IPtables configuration. You can also use the DROP command instead of REJECT.
Close a port in IPtables – CentOS 7
firewall-cmd --zone=public --remove-port=80/tcp firewall-cmd --runtime-to-permanent firewall-cmd --reload
Just switch the 80 for the port number you wish to close then run the rest of the command to commit that to the firewall configuration.
Join The Discussion.
How was this article? – Open and Close Ports using IPTables
You might also like
More from All About Linux
Disable Cors Protection Allow Website Through Cors Protection (Corss-origin Resource Sharing) Cors is a resource that allows or disallows resource usage …