How to Close and Open Ports with iptables

Linux dedicated servers typically rely a software firewall system called iptables. With it you can control which ports allow inbound and/or outbound access. It is very important to have iptables configured properly, both for your server’s functionality and for its security.

There are many tools, both command-line based and web-based that allow you to control and configure iptables. In some cases, particularly emergency situations, you may still prefer or need to use the command line. In such situations, here is an easy guide to follow.

As an example, let’s suppose you want to open the TCP port 25 for your SMTP server.

1. Login to your server via SSH
2. Become root:
3. Enter the following command:

iptables -A INPUT -p tcp --dport 25 -j ACCEPT

On the other hand, if you wanted to close access to the same port, you would enter:

iptables -A INPUT -p tcp --dport 25 -j DROP

Once you are finished, save and restart iptables

/etc/init.d/iptables save
/etc/init.d/iptables restart


1. Some Linux distributions, such as Red Hat Enterprise Linux and CentOS provide basic iptables management through the “setup” program. Simply run “setup” as root and configure the firewall.

2. If your server uses a web-based control panel to configure the firewall, it is not a good idea to manually play with it except in cases of emergency where you cannot access services (such as the web).

3. Some iptables management software allows you to control it without actually having to use the iptables command. One good option for this is APF.