NodeJS

From Gentoo Wiki
Jump to: navigation, search
Warning
This is a work in progress!

About Installation

This guide will walk through installing Node.js behind nginx and using Monit to keep Node instances alive. Since Node.js is a single-process application, the goal is to launch multiple instances of the application and load balance using nginx.

Installation

USE flags

USE flags for net-libs/nodejs A JavaScript runtime built on Chrome's V8 JavaScript engine

inspector Enable V8 inspector
npm Enable NPM package manager
snapshot Enable snapshot creation for faster startup
systemtap Enable SystemTAP/DTrace tracing

npm

Node.js has a USE flag to include npm, the Node.js package manager. npm is necessary to install a Node.js application's dependencies, which are defined in a file named package.json. The USE can be disabled if npm is not necessary locally, or prefer to only install an alternative, for example, sys-apps/yarn.

Web application daemons with nginx and monit

Packages

Node.js typically responds directly to HTTP requests by running a server. Node.js works best with multiple instances running behind a load-balancing gateway, such as nginx.

Use app-admin/monit for spawning Node.js servers.

root #emerge --ask monit nginx nodejs

Configure Monit

FILE /etc/monit.d/my-appAuto restart NodeJS App
check process mysql with pidfile /var/run/my-app/mysqld.pid
    start program = "/bin/bash -c 'rc-service mysql start'"
    stop program  = "/bin/bash -c 'rc-service mysql stop'"

Configure Nginx

FILE /etc/nginx/nginx.confNginx Config
http {
    upstream myapp1 {
        least_conn;
        server srv1.example.com;
        server srv2.example.com;
        server srv3.example.com;
    }
 
    server {
        listen 80;

        location / {
            proxy_pass http://myapp1;
        }
    }
}

Web application with openrc runscript

FILE /etc/init.d/nodejs-serverSample init.d file for a Node.js daemon
#!/sbin/openrc-run
 
user="nobody"
group="nobody"
command="/usr/bin/node"
directory="/opt/${RC_SVCNAME}"
command_args="httpd.js"
command_user="${user}:${group}"
command_background="yes"
pidfile="/run/${RC_SVCNAME}.pid"
output_log="/var/log/${RC_SVCNAME}.log"
error_log="${output_log}"
 
depend() {
	use net
}