Socket.io implementation is working in local but gest timed out when hosted on Nginx

I’m running a Node.js application on a server that communicates via WebSockets using the Socket.IO library. The Node.js application listens on port 5000, and I am using NGINX as a reverse proxy to handle incoming WebSocket connections and API requests.

I am experiencing a WebSocket connection error while trying to connect to my server running on ws://137.184.232.75:5000/socket.io/?EIO=4&transport=websocket. The server is supposed to handle WebSocket connections, but the connection keeps failing with the following error messages in the browser console:

WebSocket connection to 'ws://137.184.232.75:5000/socket.io/?EIO=4&transport=websocket' failed:
WebSocket connection error: tc: websocket error.

What I’ve tried:

Server Configuration

The server is set up using Node.js with Socket.IO, and it’s listening on port 5000. I confirmed this using lsof -i :5000.
I’ve confirmed that the server is running and should be capable of handling WebSocket connections.

Firewall Rules

I’ve checked that port 5000 is open. I even temporarily disabled the firewall to ensure it’s not blocking the connection.

Nginx Reverse Proxy (If Applicable)

I’ve configured Nginx to handle WebSocket connections by adding the necessary proxy_pass, proxy_http_version, and proxy_set_header directives

server {
    listen 80;
    server_name 137.184.232.75; 

    root /var/www/app.example.com/public_html/example/browser;
    index index.csr.html index.html index.htm;

    location / {
        try_files $uri $uri/ @node_server;
    }

    location @node_server {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    location /socket.io/ {
        proxy_pass http://localhost:5000/socket.io/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    location /api/ {
        proxy_pass http://localhost:5000/api/;
        proxy_http_version 1.1;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
    }

    location /api/users/uploads/ {
        alias /var/www/backend/userUploads/;
        autoindex on;
        access_log /var/log/nginx/uploads_access.log;
        error_log /var/log/nginx/uploads_error.log debug;
    }

    location ~* ^/assets/.*.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires max;
        log_not_found off;
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;

    location = /50x.html {
        root /usr/share/nginx/html;
    }

    location = /404.html {
        root /usr/share/nginx/html;
    }
}

Logs

The server logs do not show any errors when the WebSocket connection attempt is made, but the connection still fails.

Client-Side Code

The client is correctly configured to connect to ws://137.184.232.75:5000/socket.io/?EIO=4&transport=websocket. The URL and port are verified to be correct

socket.config.ts

import { SocketIoConfig } from 'ngx-socket-io';

//For production, change the configuration
// export const socketConfig: SocketIoConfig = {
//   url: 'http://localhost:5000', // Your backend server URL
//   options: {
//     transports: ['websocket'], // Use WebSocket transport only for better performance
//     autoConnect: false, // Disable auto-connect to manually manage the connection
//     reconnectionAttempts: 5, // Number of reconnection attempts
//     timeout: 60000, // Connection timeout (milliseconds)
//   },
// };

export const socketConfig: SocketIoConfig = {
  url: 'ws://137.184.232.75:5000/socket.io/', // Your backend server URL
  options: {
    path: '/socket.io',
    transports: ['websocket', 'polling'], // Use WebSocket transport only for better performance
    autoConnect: true, // Disable auto-connect to manually manage the connection
    reconnectionAttempts: 5, // Number of reconnection attempts
    timeout: 60000, // Connection timeout (milliseconds)
  },
};

socket.service.ts
import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { Socket } from 'ngx-socket-io';
import { isPlatformBrowser } from '@angular/common';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class SocketService {
  constructor(
    private socket: Socket,
    @Inject(PLATFORM_ID) private platformId: Object
  ) {}

  connect() {
    if (isPlatformBrowser(this.platformId) && !this.socket.ioSocket.connected) {
      console.log('Attempting to connect to WebSocket...');
      this.socket.connect();

      this.socket.ioSocket.on('connect', () => {
        console.log('WebSocket connection established');
      });

      this.socket.ioSocket.on('connect_error', (err: any) => {
        console.error('WebSocket connection error:', err);
      });

      this.socket.ioSocket.on('disconnect', () => {
        console.log('WebSocket connection disconnected');
      });
    }
  }

  disconnect() {
    if (this.socket.ioSocket.connected) {
      console.log('Disconnecting WebSocket...');
      this.socket.disconnect();
    }
  }

  listen(eventName: string): Observable<any> {
    console.log(`Listening for event: ${eventName}`);
    return this.socket.fromEvent(eventName);
  }

  emit(eventName: string, data: any): void {
    console.log(`Emitting event: ${eventName} with data:`, data);
    this.socket.emit(eventName, data);
  }
}

SSH Tunnel Configuration

The server uses an SSH tunnel to connect to a remote MongoDB instance. I’ve hard-coded the SSH private key path and ensured the key permissions are correctly set (chmod 600). Despite this, the SSH connection fails with an “Invalid username” error, which is logged in the server logs.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật