Multiple ports on nginx

Posted February 21, 2017 38.3k views
NginxUbuntu 16.04

I have my main site successfully running with https proxy to my localhost:5000.

I need to also route websocket traffic from mydomain:4000 to localhost:4001.

I can’t get this to work with nginx. I don’t get any build errors, but my websocket can’t connect.

Here is my sites-default file:

Default server configuration

server {
listen 80;
listen [::]:80 defaultserver ipv6only=on;
return 301 https://$host$request

listen 4000;
listen [::]:4000;

location / {
proxysetheader X-Real-IP $remoteaddr;
setheader X-Forwarded-For $proxyaddxforwardedfor;
setheader X-NginX-Proxy true;
pass https://localhost:4001/;
proxysetheader Host $httphost;
cachebypass $httpupgrade;
proxyredirect off;
httpversion 1.1;
setheader Upgrade $httpupgrade;
proxysetheader Connection “upgrade”;
proxysetheader Host $host;


HTTPS — proxy all requests to the Node app

server {
# Enable HTTP/2
listen 443 ssl http2;
listen [::]:443 ssl http2;

# Use the Let’s Encrypt certificates
ssl_certificate /etc/letsencrypt/live/;
ssl_certificate_key /etc/letsencrypt/live/;

# Include the SSL configuration from
include snippets/ssl-params.conf;

location / {
    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_pass https://localhost:5000/;
    proxy_ssl_session_reuse off;
    proxy_set_header Host $http_host;
    proxy_cache_bypass $http_upgrade;
    proxy_redirect off;
    proxy_http_version 1.1;
 proxy_set_header Upgrade $http_upgrade;
 proxy_set_header Connection "upgrade";
proxy_set_header Host $host;


  • Can you give some more hints with output from your nginx error log?
    Because so far it seems correct, but little difficult to read, when you don’t include all configs in code-blocks.

  • I’m not getting any nginx errors. The test passes and nginx starts.

    The problem is in trying to access the server.

    I have 2 services running; an https web server on port 5000 and a websocket on port 4001. Both of these services are running off the same node.js app.

    I can successfully connect to the web app at That works perfect.

    I have arduino devices that make a websocket connections to port 4000. That is what is not able to connect. The arduino tries to create a connection at I need this to route to localhost:4001.

    I am not sure if my listen ports are incorrect, or I’m doing the proxy wrong. I’m new to nginx so I’m a bit lost.

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Submit an Answer
2 answers

hi @josh2633520652c0fb3db80b1c do you figure out the problem i think i have the same issue

@oska have you got solution for the same issue?