Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deploy nodejs app on php/apache server?

I have a dedicated server on which I am currently running 4 PHP websites. The server is configured with apache+nginx. Whenever I host php websites I put files on public_html folder and thats it, it starts running. But now I want to install nodejs application. I am just confused on how to handle server.js file? and how to keep it running? should I use pm2 or forever to keep it running forever on my ubuntu host. Also how to run website with the domain name like example.com

like image 313
John Avatar asked Sep 16 '15 09:09

John


1 Answers

In NodeJS you can either use something pre-existing like express or basically roll your own webserver, which dispite sounding daunting is actually a simple in nodejs...

var http = require("http");

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}).listen(3000);

Forever and PM2 are the best place to start if you want to keep the service running on your server. Forever has been around longer than PM2, but i believe that PM2 is more feature rich than Forever (forever being slightly simpler to use).

In regards to apache or nginx you can use those to forward requests onto your node process. http by default runs over port 80, howerver port 80 will already be being used by your apache process. What I recommend is to run your nodejs application on another port (for example 3000) and use your existing web server (apache, ligtthpd, nginx etc) as a reverse proxy, I've included a examples setups below.

Apache

<VirtualHost example.com:*>
    ProxyPreserveHost On

    ProxyPass /api http://localhost:3000/
    ProxyPassReverse /api http://localhost:3000/

    ServerName localhost
</VirtualHost>

Lighttpd

$HTTP["host"] == "example.com" {
    server.document-root = "/var/www/example.com"
    $HTTP["url"] =~ "(^\/api\/)" {
       proxy.server = (
            "" => (
                (
                    "host" => "127.0.0.1",
                    "port" => "3000"
                )
            )
        )
    }
}

nginx

http {

    ...

    server {

        listen 80;
        server_name example.com;

        ...

        location /api {

            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Scheme $scheme;

            rewrite ^/api/?(.*) /$1 break;
            proxy_pass http://localhost:3000;
        }

        ...
    }
}

In the above examples any request to http://example.com/api would be redirected to your node process running on port 3000.

The idea is here that you use webserver for serving up your static files (for example css) and your node process for serving up your application.

like image 149
Kinetic Avatar answered Sep 20 '22 23:09

Kinetic