Running node.js on port 80 with apachePosted: May 21, 2012
This weekend I was faced with the task of putting a nodejs application into production mode.
Most of the development happened offline with each developer running local instances of node and using git to synchronize the code, so we didn’t have the problem of configuring node in a centralized server. Now that the development stage is over, we needed to set the project into production mode.
We already use Linode to host some of our projects, so we decided to host the nodejs project there as well.
All of our current projects are being served via apache.
The problem is that we can’t set apache and node to listen on the same port (80) and we didn’t have the option of deactivating apache to run just node.
We decided to implement a quick solution to get both apache and node working together: Proxy mode
So apache can still listen on port 80, and whenever somebody requests the nodejs application we forward the request to the port node is listening, in our case 11342.
Below are the steps needed to get apache and node running on the same server:
Assuming you already have apache2 installed and the nodejs application set up.
Load proxy modules
Load the proxy modules that will forward the request to node:
Open the file apache2.conf
Usually the file is located in the dir /etc/apache2/
If you not sure where the file is:
cd / sudo find -name "apache2.conf"
After opening, append the following lines at the bottom of the file:
LoadModule proxy_module /usr/lib/apache2/modules/mod_proxy.so LoadModule proxy_http_module /usr/lib/apache2/modules/mod_proxy_http.so
Without adding those modules, if you try to start apache you will get this message:
Syntax error on line 6 of /etc/apache2/sites-enabled/mysite.com:
Invalid command ‘ProxyRequests’, perhaps misspelled or defined by a module not included in the server configuration
Action ‘configtest’ failed.
The Apache error log may have more information.
Configure the vhost
Now that you have the required modules running, it is time to configure the vhost
To add a vhost to apache you need to create a file in /etc/apache2/sites-available
<VirtualHost *:80> ServerAdmin firstname.lastname@example.org ServerName mysite.com ServerAlias www.mysite.com ProxyRequests off <Proxy *> Order deny,allow Allow from all </Proxy> <Location /> ProxyPass http://localhost:11342/ ProxyPassReverse http://localhost:11342/ </Location> DocumentRoot /srv/www/mysite/public_html/ ErrorLog /srv/www/mysite/logs/error.log CustomLog /srv/www/mysite/logs/access.log combined </VirtualHost>
First you specify that all requests on port 80, to the domain mysite.com should be forward to localhost at port 11342
Enable the vhost
Now you need to enable the new vhost:
A link will be created in the sites-enabled dir
to disable the site:
Last thing you need to do is restart apache:
service apache2 reload
You should get the message:
* Reloading web server config apache2 [ OK ]