Blog

Apache and NodeJS on the Same Server

Jul 15 2016

Apache NodeJS Systems Backend

Running Apache and NodeJS on the same server is simple. On my development machines I run a virtual document root so adding new domains can be done without restarting apache.

Load Apache Modules

Be sure Apache is running loading the two modules below by uncommenting them.

In Centos7 these moved to vim /etc/httpd/conf.modules.d/00-proxy.conf

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

Configure the Document root

We need to tell apache that all traffic for this specific domain needs to be rerouted to Node Js but my existing virtual document root handles everything and looks like this: vim /etc/httpd/conf.d/virtual.conf

<VirtualHost *:80>
  UseCanonicalName Off
  VirtualDocumentRoot /var/www/virtual/%-2.0.%-1/%-3/public
  ErrorLog logs/error_log
  CustomLog logs/access_log common
  RewriteEngine On
  RewriteCond %{HTTP_HOST} !^www\.[a-z0-9]+\.[a-z]{2,6} [NC]
  RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
  RewriteCond %{HTTPS}s ^on(s)|
  RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>

The new rules need to be added below the existing ones. So append this next block to the bottom of the file. You will need to change the domain and port to match your node servers.

<VirtualHost *:80>
  ServerName jasonbrennan.com
  ServerAlias www.jasonbrennan.com
  DocumentRoot /var/www/virtual/jasonbrennan.com/www/public
  ProxyPass / https://localhost:8000/
  ProxyPassReverse / https://localhost:8000/
</VirtualHost>

Restart & Test

Run service httpd restart and test the domain in your browser. Everything should be working fine.

Trouble If you see the following error in your console or your assets aren't loading, you're likely missing the trailing slashes after your proxy URL's.

Apache reverse proxy “Failed to load resource” 502 Proxy Errror




Menu

Contact Us

Contact form submitted!
We will be in touch soon.