How to use Node.js with Apache on port 80

My latest project uses Node.js, but I want to host it on a subdomain of my webserver – which runs Apache. Typically this would involve setting up another IP address so that you could bind Apache to your original IP and your Node app to your new IP. This would result in both servers running on port 80 and you can assign your subdomain to the new IP.

However… IPv4 addresses are extremely limited and I don’t particularly want to pay for another IP. Luckily, this problem can be solved with a little bit of Apache know-how.

First you will want to locate your httpd.conf – this varies from system to system. The first thing you want to make sure of is that mod_proxy is loaded and not commented out. Secondly, you want your Node app to bind to a high port on the same IP as your webserver. I’ll be using port 3000 for this project. Finally, of course, you want to edit your DNS entries and add a new entry for the subdomain which points at the same IP as your main domain.

Also make sure that you have a NameVirtualHost directive in your httpd.conf (which you should if you are already using vhosts). If not, I like to use NameVirtualHost *:80.

With this configuration in place, we can use mod_proxy to proxy requests for that subdomain through to the Node server using name-based virtual hosts. That’s a mouthful, but it’s trivial to implement in httpd.conf:

<VirtualHost *:80>
ServerName subdomain.yourdomain.com
ProxyPreserveHost on
ProxyPass / http://localhost:3000/
</VirtualHost>

Viola! All requests for the subdomain will now be proxied to your local Node app’s server.