Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm running Ubuntu Server (natty) in as a gateway/firewall in front of a private network. I have successfully enabled IP forwarding and NAT so the machines behind the firewall can connect to Internet (followed the instructions from

What I want now, is that a specific IP behind this firewall, whenever wants to connect to an external service to enforced to use only a specific port: (application) -> (gateway, fictive ip) -> (service, fictive ip)

So whenever wants to connect to I want it t be enforced by router to use port 10002 (from port range 10002-12000). allows connections from gateway to ports 10002-12000.

Is there a way to create a custom chain and plug it into ufw, so that I will still be able to use ufw in the intended way and be able to dynamically update this chain whenever I add machines behind this firewall.

share|improve this question
up vote 3 down vote accepted

You can do that by adding a iptables rule using REDIRECT to redirect all requests done by a --src on a specific --dport to be redirected to another specific --to-ports

I would look something like this:

iptables -t nat -I OUTPUT --src --dst -p tcp --dport 80 -j REDIRECT --to-ports 10002


Correct answer was supplied by Calin Don after testing:

iptables -t nat -I PREROUTING --src --dst -p tcp --dport 11000:12000 -j DNAT --to-destination

share|improve this answer
I have tried it, but it doesn't work. What works instead is: iptables -t nat -I PREROUTING --src --dst -p tcp --dport 11000:12000 -j DNAT --to-destination – Calin Don Oct 4 '11 at 13:07
Well, gj then! ;) – Bruno Pereira Oct 4 '11 at 13:52

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.