IPTables only allow localhost access

I have struggled throughout the years to get a solid understanding on iptables. Any time I try and read through the man pages my eyes start to glaze over.

I have a service that I only want to allow the localhost to have access to.

What terms (or configuration, if someone is feeling generous) should I Google for to allow only localhost host to have access to a given port?


If by service you mean a specific port, then the following two lines should work. Change the "25" to whatever port you're trying to restrict.

iptables -A INPUT -p tcp -s localhost --dport 25 -j ACCEPT
iptables -A INPUT -p tcp --dport 25 -j DROP

I'd recommend:

iptables -A INPUT -i lo -p tcp --dport $APP_PORT -j ACCEPT
iptables -A INPUT -p tcp --dport $APP_PORT -j DROP

Because, self-addressed packets do not necessarily have 127.0.0.1 as its source, but they all 'enter' from the lo interface.

Now, if you really want to understand iptables the first thing you should do is to download and print good diagrams explaining the relations of the netfilter tables. Here are two great ones:

  • http://en.m.wikipedia.org/wiki?search=iptables - very complex, but the refrence
  • http://vinojdavis.blogspot.com/2010/04/packet-flow-diagrams.html - the upper diagram is much more understandable, though not as complete

Finally, read a lot of iptables HOWTO's. The practical examples would help you get up-to-speed real quick :)