Apache and NodeJS on the Same Server
Running Apache and Node.js applications on the same server using Apache's proxy modules
Running Apache and Node.js on the Same Server
Running Apache and Node.js on the same server is straightforward. On my development machines, I use a virtual document root setup, so adding new domains doesn’t require restarting Apache.
Load Apache Proxy Modules
First, ensure Apache is loading the required proxy modules. Uncomment these lines in your Apache configuration:
On CentOS 7:
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 Document Root
My existing virtual document root configuration handles all domains dynamically and looks like this:
<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>
Add Node.js Proxy Configuration
Append this new VirtualHost block to the bottom of your virtual configuration file. Update the domain and port to match your Node.js server:
<VirtualHost *:80>
ServerName jasonbrennan.com
ServerAlias www.jasonbrennan.com
DocumentRoot /var/www/virtual/jasonbrennan.com/www/public
ProxyPass / http://localhost:8000/
ProxyPassReverse / http://localhost:8000/
</VirtualHost>
How It Works
- ServerName/ServerAlias: Defines which domains this configuration applies to
- DocumentRoot: Sets the local document root (can be used for static assets)
- ProxyPass: Forwards all requests (
/) to the Node.js server on localhost:8000 - ProxyPassReverse: Rewrites redirects from the backend to maintain proper URLs
Restart and Test
Restart Apache and test your domain:
service httpd restart
Visit your domain in a browser - requests should now be handled by your Node.js application.
Troubleshooting
If you encounter errors like “Failed to load resource” or 502 Proxy Errors, you’re likely missing the trailing slashes in your proxy URLs. Ensure they end with /:
# Correct
ProxyPass / http://localhost:8000/
ProxyPassReverse / http://localhost:8000/
# Incorrect
ProxyPass / http://localhost:8000
ProxyPassReverse / http://localhost:8000
Benefits
This setup allows you to:
- ✅ Run Apache for traditional web hosting
- ✅ Run Node.js applications on the same server
- ✅ Use domain-based routing (Apache handles routing, Node.js handles the app)
- ✅ Maintain existing Apache configurations for other sites
- ✅ Scale by running multiple Node.js applications on different ports
The virtual document root continues to handle all other domains, while specific domains can be routed to Node.js applications as needed.