How to Run Node.js on Apache Server
If you have your website running on apache but also want to have node.js serve some of your url. In this tutorial, I’m going to show you how to use reverse proxy technique to make apache be able to run node.js application on the same server. Let’s go check it out!
Since we cannot run the both node.js and apache to listen the same port. we’ll to config apache to act like a reverse proxy and pass the request to node.js application for a specific url. For example, if you already have Apache server running on localhost and want to run Node.js app on localhost/node, the flow should looks like this
First let’s start the node application to listen on port 3000.
const express = require('express') const app = express() app.get('/', (req, res) => res.send('Hello World! from Node.js')) app.listen(3000, () => console.log('Example app listening on port 3000!'))
This is the simple app to listen for http request using Express and return a simple text which you will be able to see it on browser if you navigate to localhost:3000
Next we will make the Apache reroute the request by using proxypass directive. Just head to httpd.conf file and add
ProxyPass /node http://localhost:3000/
You can change the /node to whatever url that you want to serve your node application
Then, make sure that you have enable the mod_proxy and mod_proxy_http modules by uncommenting it
LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_http_module modules/mod_proxy_http.so
Save the file, and reboot the Apache server.
Currently if you navigate to local, this page is running on apache.
Now let’s navigate to localhost/node.
It’s worth to note that this approach is suitable for a specific role with limited number of users. But if you want to have the performance scalablity, you’ll need to to run both apache and node.js separately and use something like nginx to do the reverse proxy instead.
I hope this should gave some idea of how it works! Feel free to leave a comment if you have any questions or feedback. And please like or subscribe to our Facebook and Youtube Channel to stay tune if you love this tutorial.