'How to setup Ngrok like server for TCP connections?

I would setup an ngrok like self-hosted server. But have some troubles with TCP connections. It works well with https protocol with below Nginx config (it forward my local web server with ssh command):

ssh -R 8888:localhost:5000 abc.xyz

upstream tunnel {
  server 127.0.0.1:8888;

}

server {
  server_name abc.xyz;

  access_log /var/log/nginx/$host;

  location / {
    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-Proto https;
    proxy_redirect off;

    proxy_pass http://localhost:8888/;
  }
    error_page 502 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }    
}

Then I step up with TCP connections with forwarding my vnc server port 5900 with below config:

  stream {
   log_format dns '$remote_addr - - [$time_local] $protocol $status $bytes_sent $bytes_received $session_time "$upstream_addr"';

    access_log /var/log/nginx/access.log dns;
    error_log /var/log/nginx/error.log;

    upstream stream_backend {
        server 127.0.0.1:5902;
    }

    server {
        listen     5903;
        #TCP traffic will be forwarded to the "stream_backend" upstream group
        proxy_pass stream_backend;
 }


}

I expect It would forward my local vnc server to internet like we could do with ngrok with ssh command.

ssh -L 5902:127.0.0.1:5900 root@ip

Is there anything wrong this that configs? Here is the acess log and error on my server after trying connect with port 5903: Error Log:

2022/02/19 09:32:54 [notice] 35807#35807: signal process started
2022/02/19 09:33:09 [error] 35808#35808: *9 connect() failed (111: Unknown error) while connecting to upstream, client: 14.186.105.235, server: 0.0.0.0:5903, upstream: "127.0.0.1:5902", bytes from/to client:0/0, bytes from/to upstream:0/0
2022/02/19 09:34:05 [error] 35808#35808: *11 connect() failed (111: Unknown error) while connecting to upstream, client: 14.186.105.235, server: 0.0.0.0:5903, upstream: "127.0.0.1:5902", bytes from/to client:0/0, bytes from/to upstream:0/0

Access Log:

14.186.105.235 - - [19/Feb/2022:09:33:09 +0000] TCP 502 0 0 0.000 "127.0.0.1:5902"
14.186.105.235 - - [19/Feb/2022:09:34:05 +0000] TCP 502 0 0 0.000 "127.0.0.1:5902"

enter image description here enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source