Home > Applications & Tools > Linux Firewall with iptables Command

Linux Firewall with iptables Command

January 12th, 2014 Leave a comment Go to comments

After proxying a service with Nginx, it’s always a good idea to block the service from direct remote access. For example, you have a tomcat server running on port 8080, and you’ve configured Nginx to proxy requests from port 80 to port 8080. The port 8080 should then be blocked from any host except localhost.

To do this on Linux, one of the ways is to just install iptables. On Ubuntu, issue the following commands to install and add rules:

Time to learn how to "Google" and manage your VMware and clouds in a fast and secure

# apt-get install iptables
# iptables -A INPUT -p tcp -s localhost --dport 8080 -j ACCEPT
# iptables -A INPUT -p tcp --dport 8080 -j DROP

There is not much to say about the installation. For the two commands after that are adding rules. The first rule says that the ip packets from localhost (-s localhost) to the port 8080 (–dport 8080) with TCP protocol (HTTP uses TCP) should be accepted. The second rule says that any packets to the port 8080 (–dport 8080) with TCP protocol should be DROPped. These two rules may sound contradict to each other, but because it’s checked sequentially it works fine.

To list existing rules:

# iptables -L -n -v

To flush out (delete) rules, just use the following commands:

# iptables -F

The rules added to iptables take effects immediately. But it does NOT persist over reboot. To achieve that, an easy way is to install another package called iptables-persistent as follows:

# apt-get install iptables-persistent
# iptables-save > /etc/iptables/rules.v4

To learn more about iptables, I found these links pretty helpful:

Linux: 20 Iptables Examples For New SysAdmins

25 Most Frequently Used Linux IPTables Rules Examples

  1. April 29th, 2016 at 04:26 | #1

    How to direct incoming traffic from a trusted network to a chain?

    -A FORWARD -i eth1 -o trusted-outside -j ACCEPT

  1. No trackbacks yet.