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

We recommend that you select one of the following labels when creating a new Node.js instance from the Website :

  • Node.js / MongoDB 2.4 (recommended)
  • Node.js / PostgreSQL 9.4 (recommended)
  • Node.js / MySQL 5.6 (Percona) (recommended)

All recommended instances have a ”(recommended)” suffix in their name.

To create a new instance using Gandi CLI or the API, choose of the following types:

  • nodejsmongodb2.4
  • nodejspgsql9.4
  • nodejsmysql5.6

Legacy instances

We do not recommend that you create new instances with the following types:

  • Node.js / MongoDB 2.4 (CLI / API: nodejsmongodb)
  • Node.js / PostgreSQL 9.2 (CLI / API: nodejspgsql)
  • Node.js / MySQL 5.5 (CLI/API: nodejsmysql)

Supported versions

Node.js 4 LTS is currently pre-installed and supported on the recommended Node.js instances. You can also use any version of Node.js and npm distributed by Node Version Manager (nvm)

See the Selection of Node.js version section below to learn how to use the “package.json” file to define your own versions.

Legacy

Legacy Node.js instances support the following versions :

  • 0.12.x (default)
  • 0.10.x
  • 0.8.x

You can also choose other versions of Node.js, but not of NPM.

Any version

You can install other versions of Node.js. Just choose any version distributed through Node Version Manager ("nvm").

Please see the Node Version Manager section below to learn how this works.

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 use any version of Node.js and npm distributed by Node Version Manager (nvm).

Simply specify the versions you want to use in your project's package.json file. For example:

{
  "engines": {
    "node": "~ 4.0",
    "npm": "*"
  }
}

Node.js legacy

.nvmrc file

Simple Hosting can use Node Version Manager (nvm) to install your preferred version of Node.js on your instance.

Create a file called ”.nvmrc” at the root of your project and write your desired version number.

When you deploy with git+ssh, Simple Hosting will detect the file (doing this via sFTP or SSH won't work). If necessary, it will then download and install the correct version using “nvm” before proceeding to installing your dependencies.

Example :

$ echo "4.4" > .nvmrc
$ cat .nvmrc
> 4.4

The presence of a ”.nvmrc” file overrides any “engines” settings from your “package.json” file.

Gandi does not verify or provide official for support Node.js binaries downloaded with nvm. Please make sure they meet your stability and security requirements yourself.

Package.json

To use one of the pre-installed versions of Node.js, you can 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.12.x. For more information about the “engines” field , 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

MySQL 5.6 (Percona) and MySQL 5.5 are available to use with Node.js instances on Simple Hosting.

You can connect to the MySQL database service through its Unix socket, available at /srv/run/mysqld/mysqld.sock. The default user is root and no password is required by default. However, you should create safe credentials for real-world usage. You can also use the default_db database for fast setups and testing purposes.

You can create as many users and databases as you need; you're only limited by your disk space, which you can increase at any moment up to 1 TB.

You can manage your MySQL database with the standard shell tools (mysql, mysqldump, etc.) via the SSH console, or from the web admin console with PHPMyAdmin. Check out the reference article about MySQL management on Simple Hosting to learn more.

Below is a minimalistic Node.js code example to test the database connection on Simple Hosting:

index.js

var http = require('http'),
    mysql = require('mysql');
 
var mysql_conn = mysql.createConnection({
  socketPath: '/srv/run/mysqld/mysqld.sock',
  database: 'default_db',
  user: 'root',
  password: ''
});
 
var test_mysql_conn = function(callback) {
  mysql_conn.connect(function(err) {
    if (err) {
      console.log(err.code);
      if (callback) callback("NOT WORKING");
    } else {
      console.log('connected...');
      if (callback) callback("OK");
    }
  });
  mysql_conn.end();
};
 
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('Hello Node.js!\n');
  test_mysql_conn(function(mysql_status) {
    res.write('MySQL connection: ' + mysql_status + '\n');
    res.end();
  });
}).listen(process.env.PORT);

package.json

{
  "name": "sample-nodejs-mysql-app",
  "version": "1.0.0",
  "description": "Sample Node.js MySQL app for Simple Hosting",
  "main": "index.js",
  "engines": {
    "node": "0.12"
  },
  "dependencies": {
    "mysql": "*"
  }
}

PostgreSQL

PostgreSQL versions 9.4 and 9.2 are both available for Simple Hosting with Node.js.

Your instance's PostgreSQL service will be reachable on localhost, at port 5432. By default, you can use the hosting-db user without a password to connect to the default database, called postgres. We recommend that you create secure credentials for real-world usage.

You can create as many users and databases as you need; you're only limited by your disk space, which you can increase at any moment up to 1 TB.

You can manage your PostgreSQL database with the standard shell commands via the SSH console (psql, pg_dump, etc.), or from the Web admin panel with phpPgAdmin. Check out the reference article about PostgreSQL management on Simple Hosting to learn more.

Below is a minimalistic Node.js code example to test the database connection on Simple Hosting:

server.js

var http = require('http'),
    pg = require('pg');
 
var pg_url = "tcp://hosting-db@localhost/postgres";
var pg_conn = new pg.Client(pg_url);
 
var test_pg_conn = function(callback) {
  pg_conn.connect(function(err) {
    if (err) {
      console.log(err);
      if (callback) callback("NOT WORKING");
    } else {
      console.log('Connected to PostgreSQL');
      if (callback) callback("OK");
    }
  });
};
 
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('Hello Node.js!\n');
  test_pg_conn(function(pg_status) {
    res.write('PostgreSQL connection: ' + pg_status + '\n');
    res.end();
  });
}).listen(process.env.PORT);

package.json

{
  "name": "sample-nodejs-pgsql-app",
  "version": "1.0.0",
  "description": "Sample Node.js PostgreSQL app for Simple Hosting",
  "main": "index.js",
  "engines": {
    "node": "0.12"
  },
  "dependencies": {
    "pg": "*"
  }
}

MongoDB

MongoDB 2.4 is the version currently available for Node.js instances on Simple Hosting.

In MongoDB-type instances, the MongoDB database service is available on localhost at port 27017. No user and password are required by default, but you should create safe credentials for real-world usage.

You can create as many users and databases as you need; you're only limited by your disk space, which you can increase at any moment up to 1 TB.

You can manage your MongoDB database from the standard mongo shell via the SSH console, or from the Web admin panel with RockMongo. Check out the reference article about MongoDB management on Simple Hosting to learn more.

Below is a minimalistic Node.js code example to test the database connection on Simple Hosting:

index.js

var http = require ("http"),
    mongo = require("mongodb");
 
var mongo_url = "mongodb://localhost:27017/sample";
var mongo_conn = mongo.MongoClient;
 
var test_mongo_conn = function(callback) {
  mongo_conn.connect(mongo_url, function(err, db) {
    if (err) {
      console.log(err);
      if (callback) callback("NOT WORKING");
    } else {
      console.log("Connected to server.");  
      if (callback) callback("OK");
    }
    if (db) db.close();
  });
};
 
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('Hello Node.js!\n');
  test_mongo_conn(function(status) {
    res.write('MongoDB connection: ' + status + '\n');
    res.end();
  });
}).listen(process.env.PORT);

package.json

{
  "name": "sample-nodejs-mongodb-app",
  "version": "1.0.0",
  "description": "Sample Node.js MongoDB app for Simple Hosting",
  "main": "index.js",
  "engines": {
    "node": "0.12"
  },
  "dependencies": {
    "mongodb": "*"
  }
}

You'll find detailed documentation about getting started and using MongoDB with Node.js in the official website.

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: 06/20/2016 at 16:59 by Alexandre L. (Gandi)