84

We have an Apache Webserver installed on a machine which also serves pages using Perl.

For a project I've decided to use Node.js instead of Perl/Ruby. Just wondering if it's possible to use Apache as my webserver (so it serves the pages) and use Node.js to dynamically create the web pages (this is for a web app I am creating)?

So in other words can they work hand in hand just like Apache/Perl or Apache/PHP etc..

svick
  • 236,525
  • 50
  • 385
  • 514
JackSparrow123
  • 1,360
  • 2
  • 18
  • 23

7 Answers7

75

Hosting a nodejs site through apache can be organized with apache proxy module.

It's better to start nodejs server on localhost with default port 1337

Enable proxy with a command:

sudo a2enmod proxy proxy_http

Do not enable proxying with ProxyRequests until you have secured your server. Open proxy servers are dangerous both to your network and to the Internet at large. Setting ProxyRequests to Off does not disable use of the ProxyPass directive.

Configure /etc/apche2/sites-availables with

<VirtualHost *:80>
    ServerAdmin admin@site.com
    ServerName site.com
    ServerAlias www.site.com 

    ProxyRequests off

    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    <Location />
        ProxyPass http://localhost:1337/
        ProxyPassReverse http://localhost:1337/
    </Location>
</VirtualHost>

and restart apache2 service.

Evgeny Karpov
  • 2,386
  • 26
  • 16
45

No. NodeJS is not available as an Apache module in the way mod-perl and mod-php are, so it's not possible to run node "on top of" Apache. As hexist pointed out, it's possible to run node as a separate process and arrange communication between the two, but this is quite different to the LAMP stack you're already using.

As a replacement for Apache, node offers performance advantages if you have many simultaneous connections. There's also a huge ecosystem of modules for almost anything you can think of.

From your question, it's not clear if you need to dynamically generate pages on every request, or just generate new content periodically for caching and serving. If its the latter, you could use separate node task to generate content to a directory that Apache would serve, but again, that's quite different to PHP or Perl.

Node isn't the best way to serve static content. Nginx and Varnish are more effective at that. They can serve static content while Node handles the dynamic data.

If you're considering using node for a web application at all, Express should be high on your list. You could implement a web application purely in Node, but Express (and similar frameworks like Flatiron, Derby and Meteor) are designed to take a lot of the pain and tedium away. Although the Express documentation can seem a bit sparse at first, check out the screen casts which are still available here: http://expressjs.com/2x/screencasts.html They'll give you a good sense of what express offers and why it is useful. The github repository for ExpressJS also contains many good examples for everything from authentication to organizing your app.

Darren
  • 1,846
  • 15
  • 22
  • 1
    Thanks Darren! Fortunately this project has long since finished! – JackSparrow123 Feb 22 '14 at 02:12
  • It's 2015, and I've just learned about Express from this post. I was wondering about pros and const of Express vs. Meteor. Express is bigger on Google Trends than meteor, but declining, and Meteor is growing. – Irina Rapoport Apr 23 '15 at 20:44
  • FYI, the folks who brought you Express are now developing Koa. I use it and love it. It makes excellent use of JavaScript's async/await syntax, which is the best way to do async. – John Deighan Apr 02 '20 at 12:57
  • If any of you are coming to Node.js from, say an OOP language, you may want to checkout Nest.js. It's basically Angular for backend development, with TypeScript and built on top of either express.js or fastify (you can pick either of these two as the engines), providing an OOP MVC architecture that express and fastify lack. – OzzyTheGiant Mar 10 '22 at 22:52
26

Although there are a lot of good tips here I'd like to answer the question you asked:

So in other words can they work hand in hand just like Apache/Perl or Apache/PHP etc..

YES, you can run Node.js on Apache along side Perl and PHP IF you run it as a CGI module. As of yet, I am unable to find a mod-node for Apache but check out: CGI-Node for Apache here http://www.cgi-node.org/ .

The interesting part about cgi-node is that it uses JavaScript exactly like you would use PHP to generate dynamic content, service up static pages, access SQL database etc. You can even share core JavaScript libraries between the server and the client/browser.

I think the shift to a single language between client and server is happening and JavaScript seems to be a good candidate.

A quick example from cgi-node.org site:

<? include('myJavaScriptFile.js'); ?>
<html>
   <body>
      <? var helloWorld = 'Hello World!'; ?>
      <b><?= helloWorld ?><br/>
      <? for( var index = 0; index < 10; index++) write(index + ' '); ?>
   </body>
</html>

This outputs:

Hello World!
0 1 2 3 4 5 6 7 8 9

You also have full access to the HTTP request. That includes forms, uploaded files, headers etc.

I am currently running Node.js through the cgi-node module on Godaddy.

CGI-Node.org site has all the documentation to get started.

I know I'm raving about this but it is finally a relief to use something other than PHP. Also, to be able to code JavaScript on both client and server.

Hope this helps.

Uei Richo
  • 281
  • 3
  • 3
  • There seems to be a few node-cgi packages in the wild - is CGI-Node the same as: https://larsjung.de/node-cgi/ ? If not would you know which is more mature/complete? – Daniel Sokolowski Nov 09 '15 at 01:57
  • 1
    This is exactly the solution I was looking for to handle dynamic content on Dreamhost and not write it in PHP. Viva la JavaScript! – Sukima Jan 05 '16 at 01:29
  • This answer more directly answers the question asked. Are there other webservers capable of running node.js scripts in the same manner you'd run a php script? – Lonnie Best Jan 27 '16 at 13:31
  • @uei No Man, I have followed thier enitre tutorials installed nodejs, but still I cannot run the node commands from shell / terminal. it says Node command not found. How did you start your index.js file from godaddy servers?? Since there is no way to run our server file and start listenting to port unless we write command on terminal – Faizan Feb 17 '16 at 21:43
  • CGI injects [process creation overhead](https://en.wikipedia.org/wiki/Common_Gateway_Interface#Alternatives). This bad effect can be reduced with [FastCGI](https://en.wikipedia.org/wiki/FastCGI) or native Apache Node.js module (like mod_php). In either case - dynamic Javascript pages with Node.js is in it's infancy – Agnius Vasiliauskas Jan 31 '18 at 08:54
5

The common method for doing what you're looking to do is to run them side by side, and either proxy requests from apache to node.js based on domain / url, or simply have your node.js content be pulled from the node.js port. This later method works very well for having things like socket.io powered widgets on your site and such.


If you're going to be doing all of your dynamic content generation in node however, you might as well just use node.js as your primary webserver too, it does a very good job at serving both static and dynamic http requests.

See:

http://expressjs.com/

https://github.com/joyent/node/wiki/modules

hexist
  • 5,151
  • 26
  • 33
  • If you run it alongside Apache Node is not actually sitting 'on top of' Apache is it? Like PHP. It's still seperate instances. Is that correct? Another question...do I need Express to create the dynamic pages or I can just use Node.js by itself? There doesn't seem to be much information on express... – JackSparrow123 Jan 17 '13 at 02:13
  • Correct, node.js runs in it's own proccess. Express handles the http request stuff, see http://expressjs.com/api.html .. it's very easy to get going, that hello world at the start of the page is all you need for your first page. If you want to generate dynamic content, you'll probably want some form of template engine to generate the content that you'll be returning via express, see: https://github.com/joyent/node/wiki/modules#wiki-templating for a good list of those. – hexist Jan 17 '13 at 03:45
  • but you can make a hello world page using pure Node.js as well, does the framework over any advantages? – JackSparrow123 Jan 17 '13 at 22:27
  • It provides you with all the routing stuff, which is essentially what you get from apache (although this is a bit more flexible / powerful). – hexist Jan 17 '13 at 22:38
1

You can always do something shell-scripty like:

#!/usr/bin/node

var header = "Content-type: text/plain\n";
var hi = "Hello World from nodetest!";
console.log(header);
console.log(hi);

exit;
Xaphiero
  • 19
  • 3
0

While doing my own server side JS experimentation I ended up using teajs. It conforms to common.js, is based on V8 AND is the only project that I know of that provides 'mod_teajs' apache server module.

In my opinion Node.js server is not production ready and lacks too many features - Apache is battle tested and the right way to do SSJS.

Daniel Sokolowski
  • 11,982
  • 4
  • 69
  • 55
0

If you're using PHP you can funnel your request to Node scripts via shell_exec, passing arguments to scripts as JSON strings in the command line. Example call:

<?php
    shell_exec("node nodeScript.js"); // without arguments
    shell_exec("node nodeScript.js '{[your JSON here]}'"); //with arguments
?>

The caveat is you need to be very careful about handling user data when it goes anywhere near a command line. Example nightmare:

<?php
    $evilUserData = "'; [malicious commands here];";
    shell_exec("node nodeScript.js '{$evilUserData}'");
?>