Can nginx be used as a reverse proxy for a backend websocket server?
You can't use nginx for this currently[it's not true anymore], but I would suggest looking at HAProxy. I have used it for exactly this purpose.
The trick is to set long timeouts so that the socket connections are not closed. Something like:
timeout client 86400000 # In the frontendtimeout server 86400000 # In the backend
If you want to serve say a rails and cramp application on the same port you can use ACL rules to detect a websocket connection and use a different backend. So your haproxy frontend config would look something like
frontend all 0.0.0.0:80 timeout client 86400000 default_backend rails_backend acl websocket hdr(Upgrade) -i WebSocket use_backend cramp_backend if websocket
For completeness the backend would look like
backend cramp_backend timeout server 86400000 server cramp1 localhost:8090 maxconn 200 check
How about use my nginx_tcp_proxy_module module?
This module is designed for general TCP proxy with Nginx. I think it's also suitable for websocket. And I just add tcp_ssl_module in the development branch.
nginx (>= 1.3.13) now supports reverse proxying websockets.
# the upstream server doesn't need a prefix! # no need for wss:// or http:// because nginx will upgrade to http1.1 in the config belowupstream app_server { server localhost:3000;}server { # ... location / { proxy_pass http://app_server; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; }}