To deploy a Node.js TCP server on Ubuntu server, I have followed this tutorial:
How To Develop a Node.js TCP Server Application using PM2 and Nginx on Ubuntu 16.04

The Nodejs TCP server application is served behind Nginx reverse proxy. Thus, we will get localhost ip address in sock.remoteAddress, instead of real ip address of the client.

To work around this issue, the tutorial suggests adding proxy_protocol on in /etc/nginx/nginx.conf like so:


stream {
    server {
      listen 3000;
      proxy_protocol on;

The proxy_protocol directive tells Nginx to use the PROXY protocol to send client information to backend servers, which can then process that information as needed.

To process the information and get the real ip address, we have to install this library, findhit-proxywrap.

npm install findhit-proxywrap 

According to their README,

This module wraps node's various Server interfaces so that they are compatible with the PROXY protocol. It automatically parses the PROXY headers and resets socket.remoteAddress and socket.remotePort so that they have the correct values.

Then, we have to make following changes to the code:


const server = net.createServer();


let proxiedNet = require('findhit-proxywrap').proxy(net);
const server = proxiedNet.createServer();

Now we will get the real sock.remoteAddress and sock.remotePort of the client connected via Nginx proxy.

Above code only work when client connect through Nginx proxy. If you connect to the TCP server directly without proxy, error will happen.

Thus, when testing the server locally, the older version of the code have to be used:

const server = net.createServer();

findhit-proxywrap library is only used when the Node.js server is behind Nginx reverse proxy.


Hopefully you are able to successfully get the real ip address. 😃
Please let me know how it goes in the comments below. Thank you for reading! 😊


  1. How To Develop a Node.js TCP Server Application using PM2 and Nginx on Ubuntu 16.04

  2. findhit-proxywrap