Home > database >  How to set up Nginx reverse proxy on the same port as the application?
How to set up Nginx reverse proxy on the same port as the application?

Time:06-07

I have an application that runs on port 5555. I have set up a reverse proxy from port 5554 to 5555 using NGINX and have basic authentication on it. Here is my default.conf file

server {
    listen 5554;
    listen [::]:5554;

    server_name 123.123.123.123;

    location / {
        auth_basic "protected gateway area";
        auth_basic_user_file /etc/apache2/.htpasswd; 
        proxy_pass http://localhost:5555;
    }
}

I need to have NGINX listen on port 5555, the same port the app is running on. Then after checking authentication, the proxy should forward the request to the actual app. However, when I change the listening ports on the config file from 5554 to 5555 and send a request to 5555, the request just bypasses the proxy.

Is this possible? If so, how?

CodePudding user response:

Technically, you cannot bind same port to two applications on same IP. The NGNIX reverse proxy works just like a lightweight server which listen the requests and to the configured validation/actions/routing/rewrite/header manipulation/domain validation/SSL offload etc. and after that the request reached to actual server which is designed to handle the request.

However, there is a way to handle it by having two IPs for same machine (there are various ways you can obtain multiple IPs for same machine like:

  • Virtual Network - A VNet can be created and same port bounded with different IPs where first IP intercept the request and forward to second IP
  • Containerization - If your application is containerized it can be achieved very easily
  • Multiple Network Cards - If multiple network cards are attached with machine and connect with network, separate IP will be there and in that case same port can be used with different IPs on same machine
  • SO_REUSEPORT feature of OS - This is quite new feature supported by NGINX with help of SO_REUSEPORT a Linux Kernel feature. If your OS support this, you can bind two applications which listens the requests from same port. But again it hasn't been designed for use case given in question. For details read: https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/#:~:text=NGINX 1.9.,IP address and port combination.
  • Related