First we can check the status of IPTables by running this command;
service iptables status
By default most systems open the ssh port 22. Now we need to get the running configurations to edit it. To do that;
iptables-save > /tmp/iptables
This command will dump the running iptables configurations in to a file and it will be like this.
# Generated by iptables-save v1.4.7 on ... *filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [39:2878] -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT -A INPUT -p icmp -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT -A INPUT -j REJECT --reject-with icmp-host-prohibited -A FORWARD -j REJECT --reject-with icmp-host-prohibited COMMIT # Completed on ...
Assume that we need to run a web server on this host. Web servers usually runs on port 80. Therefore, we need to allow port 80. To allow that we can add a line similar to the ssh rule.
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT -A INPUT -j REJECT --reject-with icmp-host-prohibited
Then you need to feed this configurations to the iptables. To do that;
iptables-restore < /tmp/iptables
Now if you run the 'service iptables status' command, you can see port 80 is also allowed in it. But if you restart the service (service iptables restart) or reboot the machine, those changes will be not there. That's because it use a default configuration file on the service initialization. This default file is different from system to system. In CentOS systems that file is locates in '/etc/sysconfig/iptables'. After all the things are complete, you can save the running iptables configurations on that file it self.
But it is better if you use an alternative method like 'cron job' to run modify this iptables configurations. To do that you need to add a cron job as root by;
@reboot /sbin/iptables-restore < /root/myiptables
The modified iptables rule set must be located on that location.
Note: In few Linux distributions there is a another firewall called 'SELinux'. If you have an issue even after changing those settings in IPTables, it is better to check SELinux settings too.