9

I'm trying to add mapping for 20K Ports (range [40k-60k]) in the nginx configuration. This config is added to nginx.conf

stream{
    server {
        listen 40000;
        listen 40001;
        .
        .
        .
        listen 60000;
        proxy_pass <backend-url>:$server_port;
     }
}

Everything works jolly-good when number of mappings is < 500. But when it's increased to 20K mappings, the delay in response is tremendous. Any work-around or any other method to add port-forwarding?

Abhishek
  • 551
  • 2
  • 5
  • 22

2 Answers2

7

Since Nginx 1.15.10 you can specify a range of ports on listen directive.

Port ranges (1.15.10) are specified with the first and last port separated by a hyphen:

listen 127.0.0.1:12345-12399;
listen 12345-12399;

More info: http://nginx.org/en/docs/stream/ngx_stream_core_module.html#listen

  • notice you should also set the resolver and server_port `resolver 127.0.0.1; proxy_pass you_server_ip:$server_port;` – Deo Leung Feb 19 '21 at 06:54
3

I'd try to do accomplish it via iptables instead of nginx

https://www.cyberciti.biz/faq/linux-port-redirection-with-iptables/

You can easily redirect incoming traffic by inserting rules into PREROUTING chain of the nat table. You can set destination port using the REDIRECT target

i.e.

iptables -t nat -A PREROUTING -p tcp --dport 1:65535 -j REDIRECT --to-ports 10000

and listen port 10000 in nginx

Related discussion: https://superuser.com/questions/440324/iptables-how-to-forward-all-external-ports-to-one-local-port

Oleg Kuralenko
  • 11,003
  • 1
  • 30
  • 40