Vojtech Rinik

Hosting Node.js apps on VPS

Posted on 2012/6/13

If you're like me, you have a couple of projects, and a VPS for running them. It's relatively cheap, and if you have a new idea, you can just run it without having to pay for anything new.

I have a server where I run some Ruby applications, and recently I found out I need to run Node.js applications. By the way, this blog is written in Node.js.

So how to run it? You have a couple of options:

Apache (or whatever is your HTTP server) proxy

You setup a virtual host in Apache, that would forward all requests to your Node.js server.

<VirtualHost *:80>
  ServerName blog.rinik.net
  ProxyPass / http://localhost:7001/
  ProxyPassReverse / http://localhost:7001/
  ProxyPreserveHost On
<Proxy *>
  Order allow,deny
  Allow from all
</Proxy>

In this example I'm forwarding traffic from blog.rinik.net to localhost:7001.

Mod Rewrite

What if you want to server some files statically with Apache? Easy. Create a virtual server pointing to some directory - in that directory create .htaccess:

RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}/$0 !-f
RewriteRule .+ http://rinik.net:4001/$0 [P]

If the file doesn't exist, a request will be made to rinik.net:4001 where the Node.js process is running.

I use this for built Spine applications. When you build a Spine app, it generates index.html, application.js, etc. You server these statically, and all other requests will be sent to your Node.js app.

WebSockets?

Here's our problem. Apache Proxy doesn't support WebSockets. To be honest, I haven't solved it yet, but it looks like I'm gonna use this:

Http Proxy

Node Http Proxy is a fast HTTP proxy written in Node.js. It supports everything: HTTP, HTTPS, Websockets and Secure Websockets.

So you start the Node Proxy on 80, and it will forward requests for Node applications to Node servers, while forward all other requests to Apache. Serving static files could be tricky, though. I will report.