How to open or close a port in IPTables

Problem

Open or close a port in IPTables firewall

tl;dr

Open a port:

iptables -I INPUT -p tcp –-dport 21 -j ACCEPT
service iptables save

Close a port:

iptables -I INPUT -p tcp –-dport 21 -j REJECT
service iptables save

Solution

Main command use to change IPTables rules has the following format:

iptables -I INPUT -p tcp –-dport 80 -j ACCEPT

This opens port 80 (HTTP) for inbound connections, such as to make your web server accessible to the Internet.

Arguments

Substitute the following arguments:

  • INPUT – use INPUT if you want your server to be reachable from the outside
  • OUTPUT – use OUTPUT if you want your server to be able to reach the outside through this port
  • tcp – connection type, TCP or UDP, keep TCP unless you know to do otherwise.
  • 22 – port number.
  • ACCEPT – use ACCEPT if you want to keep the port open
  • REJECT – use REJECT if you want to keep the port closed

Save your rule

While your rule will take effect immediately, you should save it to /etc/sysconfig/iptables so it persists upon reboot.  You can do this via:

service iptables save


Was this article helpful?

mood_bad Dislike 4
mood Like 7
visibility Views: 25636