Node.js instance family

Simple Hosting Node.js makes it easy and affordable to host scalable Node.js applications.

Prerequisites

  • Knowledge of Node.js and the HTTP protocol,
  • Your site must use NPM to handle its dependencies

Version support

Versions 0.12.x, 0.10.x and 0.8.x are currently supported at the moment.

The default version is always the latest one among those installed, currently 0.12.x. To choose the Node.js version to execute your application, see Selection of Node.js version.

It is difficult to know for how long we'll be able to support each version, given that the Node.js project does not manage life cycles yet.

General functioning

Your Node.js application must be composed of at least a file called server.js. This file will be executed by the Node.js interpreter when your instance is started, or during a deployment with the Git access. In order to receive HTTP and HTTPS requests, your application must listen to port specified by the environment variable PORT (process.env.PORT).

vhosts

Contrary to PHP instances, each creation of a vhost does not create a specific directory on your disk. The directory named “default” present in your vhosts allows you to manage the data for your Node.js instance. Only one instance of your application is executed, and must manage all the vhosts that you have associated to your Simple Hosting instance.

Examples

Here is an a simple Node.js application that displays the name of the vhost.

server.js

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write('Hello Node.js!\n');
    if ('host' in req.headers) {
        var host = req.headers['host'];
        res.write('Vhost is ' + host.split(':')[0] + '\n');
    } else {
        res.write('No vhost specified\n');
    }
    res.end();
}).listen(process.env.PORT);

You can see a vhost example with express.js at https://github.com/visionmedia/express/blob/master/examples/vhost/index.js

You can also check out more Simple Hosting Node.js tutorials.

Boot

Simple Hosting supports 3 ways to boot a Node.js application.

The platform tries to boot your application using the following sequence:

  1. Use the “start script” field in package.json
  2. Use the “main” field in package.json
  3. Use a server.js file if it exists at the root of the application

The boot order changed in December 2015. server.js used to be the first file to be checked.

Please check below for more information on each of these options.

The standard way to boot a Node.js application is to use settings from npm's package.json file. Simple Hosting did not support this feature before, but it is now the recommended way to boot your application.

The package.json file needs to be placed at the root of your project. It must contain either a package.json[“main”] property defining the application's entrypoint (the file to run at boot), or a specific boot command defined in package.json[“scripts”][“start”].

Most pre-packaged Node.js applications, like Ghost, will already use this convention, making it easier to install them.

Defining an entry point

You can define an entry point using the main field. Simply enter the name of the file to boot from, and Simple Hosting will use “node” to run it.

For example, to boot from the “index.js” file:

package.json

{
  "name" : "foo",
  "version" : "1.2.3",
  "description" : "A packaged foo fooer for fooing foos",
  "main" : "index.js",
}

Running a custom command

You can also define the entire command to run by setting the ['scripts']['start'] field. Simple Hosting will simply execute this command to boot the application.

The following example is the equivalent of using the “entry point” technique described above.

package.json

{
  "name" : "foo",
  "version" : "1.2.3",
  "description" : "A packaged foo fooer for fooing foos",
  "scripts": {
    "start": "node index.js"
  }
}

The start script is very flexible and provides a variety of nice feaures to customize the way your application runs. For example, you can support ES6 by running in harmony mode.

package.json

{
  "name" : "foo-ecma-script",
  "version" : "6",
  "description" : "ES6 on Simple Hosting",
  "engines": {
    "node": ">=0.12"
  },
  "scripts": {
    "start": "node --harmony index.js"
  }
}

Combined with environment variables, you can use this feature to launch your application with a process manager like pm2 and manually control your process lifecycle. Or even try some fun stuff with threads and libuv.

Using server.js (default)

The simplest way to create a Node.js application for Simple Hosting is to create a file named server.js at the root of your project.

This was the default boot method until December 2015.

Environment variables

Your application can rely on environment variables for a number of configuration options, set by the platform or by yourself at launch time.

Here are a few examples of environment variables set by the platform before your application is booted:

  • PORT=8080
  • NODE_ENV=production
  • WEB_MEMORY=128
  • WEB_CONCURRENCY=2

WEB_MEMORY and WEB_CONCURRENCY values depend on your instance type (S, M, L, XL, XXL). The former is always set at the maximum for your instance type. The latter is our recommendation based on the instance size, but you can adapt it to suit your needs.

Accessing environment variables

You can retrieve environment variables from your application in the normal fashion, by accessing process.env. For example:

var port = process.env.PORT;
console.log(process.env.PORT);
// 8080

Setting environment variables

You can set or override environment variables from within your application or at boot time using the start script.

From within the application, you can simply set the value of an environment variable with `process.env`. For example:

process.env.NODE_ENV = "staging";
console.log(process.env.NODE_ENV); // => "staging"

At boot time, use package.json['scripts']['start'] to set one or more environment variables in shell style. For example:

package.json

{
...
  "scripts": {
    "start": "NODE_ENV=staging node index"
  }
}

Make sure you're not overriding the PORT environment variable, as your application might not be reachable afterwards. In general, make sure you're not overriding any important setting before launching your application with a custom command.

Dependencies installation of your site

The Node.js Simple Hosting platform takes care of the booting of your instance during a deployment via your Git access, and installing the dependencies of your website. For this, you must specify the dependencies in the “package.json” file at the root of your vhost:

package.json

{
  "name": "website",
  "version": "0.0.1",
  "dependencies": {
    "express": "3.x"
  }
}

Selection of Node.js version

You can choose the Node.js version to use for your application.

You only need to set the [“engines”][“node”] field in the package.json file.

package.json

{
  "name": "website",
  "version": "0.0.1",
  "engines": {
    "node": ">= 0.12"
  }
}

The example above will force the use of Node.js 0.8.x. For more information about the field “engines”, see https://docs.npmjs.com/files/package.json#engines.

Websockets

We're currently running a beta program for Websockets support.

This beta program is only available in our Paris datacenter and requires an M-size instance and an SSL certificate.

You can learn more about Websockets support in our Wiki or contact our support team if you need help.

Logs

The standard output and errors of your website are sent to a log file on your disk:

  • via the SSH console: /srv/data/var/log/www/nodejs.log
  • via SFTP: /lamp0/var/log/www/nodejs.log

This log file also contains the output of the NPM program that is in charge of your website's dependencies.

Additionally, you can view the history of actions taken by the program in charge of launching your site:

  • via the SSH console: /srv/data/var/log/www/nodejs-watchd.log
  • via SFTP: /lamp0/var/log/www/nodejs-watchd.log

You can also see if your Node.js application has correctly booted.

Database

MySQL

    connection: {
        socketPath: '/srv/run/mysqld/mysqld.sock',
        user: 'user',
        password: 'pwd',
        database: 'db',
        charset: 'utf8'
    }

Full example:

var mysql = require('mysql');
var connection = mysql.createConnection({
socketPath: '/srv/run/mysqld/mysqld.sock',
user: 'myUser',
password : 'myPassword',
database: 'myDB'
});
connection.connect(function(err) {
        if(err) {
                console.log(err.code);
        } else {
        console.log('connected...');
        }
});
connection.end();

PostgreSQL

At the moment, the Node.js instance comes with the PostgreSQL database. Note that PostgreSQL9.2 now supports the JSON data type; meaning that you can now directly store JSON data fields. You can also manipulate existing tables and output its data to clients as JSON using array_to_json and row_to_json functions.

Full example to use Node.js with PostgreSQL:

server.js

var http = require('http');
var pg = require('pg');
 
var conString = "tcp://pguser:password@localhost/mycms";
 
function list_articles(callback) {
    var client = new pg.Client(conString);
    client.connect(function(err) {
        if (err) {
            callback(null, err);
        } else {
            client.query('SELECT * FROM articles ORDER BY art_id DESC;',
                         callback);
        }
    });
}
 
function handle_error(res) {
    res.writeHead(500, {'Content-Type': 'text/plain'});
    res.end('Internal Server Error\n');
}
 
function write_response(res, result) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write('Number of articles: ' + result.rowCount + '\n');
    result.rows.forEach(function(row) {
        res.write(row.art_id + ' | ' + row.art_title + '\n');
    });
    res.end();
}
 
server = http.createServer(function(req, res) {
    list_articles(function(err, result) {
        if (err) {
            console.log(err);
            handle_error();
        } else {
            write_response(res, result);
        }
    });
});
 
server.listen(process.env.PORT);

package.json

{
  "name": "website",
  "version": "0.0.1",
  "dependencies": {
    "pg": "0.x"
  }
}

MongoDB

It is now possible to create Node.js/mongoDB instances.

Known issues

PostgreSQL

The installation of the pg module does not work with the npm version that is delivered with Node.js 0.10.x. It is therefore recommended that you chose version 0.8.x de Node.js, by following the instructions in the section concerning the choice of your Node.js version.

While installing pg module, the following errors messages might show up:

gyp WARN EACCES user "root" does not have permission to access the dev dir "/srv/data/.node-gyp/0.8.22"
gyp WARN EACCES attempting to reinstall using temporary dev dir "/srv/data/tmp/.node-gyp"
You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application.
gyp: Call to 'pg_config --libdir' returned exit status 1. while trying to load binding.gyp
gyp ERR! configure error 
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:416:16)
gyp ERR! stack     at ChildProcess.EventEmitter.emit (events.js:99:17)
gyp ERR! stack     at Process._handle.onexit (child_process.js:678:10)
gyp ERR! System Linux 3.4.7-grsec-paas-19c573d
gyp ERR! command "node" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /srv/data/web/vhosts/default/node_modules/pg
gyp ERR! node -v v0.8.22
gyp ERR! node-gyp -v v0.8.5
gyp ERR! not ok 

The pg module is in fact installed, but will be limited to the Javascript implementation. The fix will be present in the next release.

See also

Last modified: 12/07/2015 at 14:48 by Alexandre L. (Gandi)