NGINX configure Websocket in NginX – how to make it available

In the proxy.conf file, at the top, write:

upstream websocket {
        server name_of_my_docker_container:8080;
}

map $http_upgrade $connection_upgrade {
        default upgrade;
        '' close;
}

server {...

Why this? The Websocket has a constantly open connection with the client. The communication lies above the http protocol. This why we need to enable an „upgrade“ of the connection.

This example addresses a name of a Docker container. It would work with any other url too.

server {
      location / {...
      }
      ...	
      location name_of_my_docker_container {
		rewrite name_of_my_docker_container/(.*) /$1  break;
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_set_header X-NginX-Proxy true;
		proxy_ssl_session_reuse on;
		proxy_set_header Host $http_host;
		proxy_cache_bypass $http_upgrade;
		proxy_redirect off;
		proxy_set_header X-Forwarded-Proto "http";
		proxy_pass http://name_of_my_docker_container:8080;
		
                // These headers need to be set in order 
                // to enable the communication:
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "Upgrade";

		proxy_set_header Connection '';
		proxy_http_version 1.1;
		chunked_transfer_encoding off;
		proxy_buffering off;
		proxy_cache off;
	}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.