Apache 2.4 + Ruby + Sinatra + Websockets

It has been almost a year since my last blog post and a great many things have happened.

I’ve dropped out of Oxford, become a Professor Adjunct at San Jose State University, and I’ve gotten a job working on VeroFiles at Memeo in Campbell, CA as one of their senior developers.

It has been quite an exciting ride.

However, this post is about getting Sinatra to work with WebSockets.

It is well documented among the Ruby community that Apache is not great at handling WebSockets and many people have moved to NGINX, Thin, or Passenger. However, I had a need to make Ruby work with Apache and I want to spread that information now.

What I had to begin with was an Apache server with a Sinatra REST service behind it. I needed to add WebSockets to the mix. I added the gem sinatrawebsockets to the mix and it worked great running in stand alone with thin. But in the production environment it just wouldn’t work so I had to reconfigure the system to have apache as the user-facing service and I used mod_proxy_wstunnel to set up a Proxy/ReverseProxy to thin which then handles the WebSockets.

In your Apache .conf file you will need to add the following:


LoadModule proxy_module /usr/lib/apache2/modules/mod_proxy.so

LoadModule proxy_module /usr/lib/apache2/modules/mod_proxy_wstunnel.so

ProxyRequests Off
ProxyPreserveHost On

<Proxy *>
# Auth changes in 2.4 - see http://httpd.apache.org/docs/2.4/upgrading.html#run-time
Require all granted
</Proxy>

<Location /websockets>
ProxyPass wss://127.0.0.1:PORT/websockets
ProxyPassReverse wss://127.0.0.1:PORT/websockets
</Location>

Where PORT is the port that thin is running on in the background. Then launch thin as a long running process and it should now work. The example from sinatra-websockets should take you the rest of the way and with very little work you should be able to get any of the other Ruby WebSocket gems working behind Apache.

Thanks to all of the other coders out there on the net that have shared the information I needed to make this work.

%d bloggers like this: