Multiple ports on nginx

February 21, 2017 281 views
Nginx Ubuntu 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
uri;
}

server{
listen 4000;
listen [::]:4000;
server_name app.mydomain.com;

location / {
proxysetheader X-Real-IP $remoteaddr;
proxy
setheader X-Forwarded-For $proxyaddxforwardedfor;
proxy
setheader X-NginX-Proxy true;
proxy
pass https://localhost:4001/;
proxysetheader Host $httphost;
proxy
cachebypass $httpupgrade;
proxyredirect off;
proxy
httpversion 1.1;
proxy
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;
server_name app.mydomain.com;

# Use the Let’s Encrypt certificates
ssl_certificate /etc/letsencrypt/live/app.mydomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/app.mydomain.com/privkey.pem;

# Include the SSL configuration from cipherli.st
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;

}
}

3 comments
  • 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 https://app.mydomain.com. 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 app.mydomain.com:4000. 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.

Be the first one to answer this question.