Vincent Fritz
Vincent Fritz

Reputation: 111

How do i configure "ws" websocket on nginx nodejs server?

I am currently trying to deploy my NODEJS application on a nginx debian remote server . It works very well in localhost. But I have some difficulties to make websocket work in remote nginx server. I use "ws" nodejs module.

This is how i declared my websocket server side :

var WebSocket_ = require('ws');
var wss = new WebSocket_.Server({port: 40510});

And this is how i opened my websocket client side :

var ws = new WebSocket('ws://localhost:40510');

I know i have to configure /etc/nginx/sites-available/default on my Nginx VPS :

Do i need to add a websocket block location and define a specific proxipass ? If yes how ?

Do I have to replace var "ws = new WebSocket('ws://localhost:40510');" by another instruction in my client side code ?

Thank you in advance for your answers !

Upvotes: 7

Views: 9602

Answers (2)

Marco Santos
Marco Santos

Reputation: 198

If you already have a server block, put this inside (usually inside sites-available or nginx.conf):

location /ws {
    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;
    proxy_pass http://localhost:40510;
}

Now, depending on your Nginx listening ports you will configure your client IP/Port (By default Nginx listens on port 80)

var ws = new WebSocket('ws://localhost:80/ws');

Full configuration file (example):

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;
    fastcgi_buffers 64 4K;

    server {
        listen       localhost:80 default_server;
        server_name  localhost;

        # Logs
        access_log /var/log/nginx/main.access.log;
        error_log /var/log/nginx/main.error.log;

        # Websocket
        location /ws {
            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;
            proxy_pass http://localhost:40510;
        }
    }
}

Upvotes: 8

Vincent Fritz
Vincent Fritz

Reputation: 111

Thank you very much

I already use a block location, with a redirection proxi reverse :

    location / {


           proxy_pass http://localhost:8888;
           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;


            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            # try_files $uri $uri/ =404;
    }

should not I use my domain name instead? Something like:

var ws = new WebSocket('http://vincentfritz-dev.fr/ws');

?

Upvotes: 1

Related Questions