Newsletter
Newsletter

Forward Ports in NGINX

Scroll down
Fred Lackey
Fred Lackey
Expert:
  • Location
    Atlanta, Georgia
  • Experience
    40+ Years

2024-09-08

7:19 AM

fredlackey

Every once in a while you need all traffic for a specific port to be blindly passed to an upstream server in NGINX. Here are the steps I use whenever the commercial version of NGINX is not available.

Step 1 : Install the Streams Module

Not much to say here. Just install the package and create a folder to contain our .conf files:

sudo apt install nginx libnginx-mod-stream
sudo mkdir /etc/nginx/streams.d

Step 2 : Include New Streams Conf Files

The default nginx.conf file does not include a stream section. And, unfortunately, most of the advice online would have you adding your stream added there. Don’t do that. Editing your nginx.conf file should never be a normal activity. Instead, add a snippet to call upon the files we add to the new streams.d folder:

stream {
   include /etc/nginx/stream.d/*.conf;
}

There will already be an events{} block at the top of the file. I generally add it just after that.

Step 3 : Add the Stream Conf File

Now for the most difficult part of the process; creating the overly-complex my-stream.conf file. Within the folder we created, add a new text file with the .conf suffix. In this example, I needed to route traffic for port 222 to my personal Gitea server. So, I named the file gitea-ssh.conf with the following contents:

server {
  listen 0.0.0.0:222;
  proxy_pass dev-srv-a:222;
}

It should be noted that, for this snippet to work, the name or address of the upstream server must be resolvable on your local network. For me, dev-srv-a is resolved without issue. If you do not have a name for that next machine, just ensure it has a static IP address and supply that instead. For example:

server {
  listen 0.0.0.0:222;
  proxy_pass 192.168.100.42:222;
}

Step 4 : Restart NGINX

Finally, check your config and restart. To check your configuration:

sudo nginx -t

If you do not see the following text, please stop and correct the files before continuing:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Once everything is good, restart the service:

sudo systemctl restart nginx

From this point forward, NGINX is blindly passing everything from the source port (the port on the end of the listen line) to the port on the end of your proxy_pass statement.

author avatar
fredlackey
Posted in Helpful Info, Programming
Write a comment
© 2024 Fred Lackey, All Rights Reserved.
Write me a message

    Messages and contact info remain private at all times.