Combining Node.js & Apache

I decided to create a small project in order to learn node.js and wanted to document some of the configuration steps I used in case anyone attempts a similar setup. My goal is to use Node for what it excels at – lightweight, psuedo real time web requests while leaving Apache in place to serve up static content.

After installing node, I installed npm (node package manager)

curl http://npmjs.org/install.sh | sh

Next I installed node-http-proxy which will let node selectively proxy certain requests

npm install http-proxy

Based on some preliminary research, using Apache to proxy for node would defeat some of the performance & scalability advantages of Node. So I decided to make Node the first layer for http requests. To get this to work (under Ubuntu) I first moved Apache over to port 9000 by editing /etc/apache/ports.conf


NameVirtualHost *:9000
Listen 9000

I also edited /etc/apache2/sites-enabled/000-default and updated the VirtualHost

Restart Apache
sudo /etc/init.d/apache restart

And you should now see Apache running on port 9000

Since I don’t want to run Node as root, I added an iptables rule to forward requests for port 80 to port 8000
iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8000

To view the new rule use
iptables -t nat -L -n -v

And should you need to delete a rule, use the index of the rule from the previous command with this command
iptables -t nat -D PREROUTING RULE_INDEX_HERE

And the last step is to create a node server that runs on port 8000 and does conditional forwarding to Apache which is now listening on port 9000. For this I created a configuration based off one provided by indexzero. You can find mine here.

Due to this bug that has been fixed but not released yet, I had to use latest code from github of node-http-proxy for this to work.

Tagged with:
 

Categories