How to Use Node.js on a Gandi Web Hosting¶
Web Hosting Node.js makes it easy and affordable to host scalable Node.js applications.
Prerequisites¶
Node.js and NPM installed on your computer.
Your application must use NPM to handle its dependencies.
Version Support¶
Actually, when you configure your node.js hosting, we propose versions 10, 12, 14 and 18. We highly recommend to use only these versions of node.js, as the ones provided by Node Version Manager (nvm) can be incompatible with our hostings.
If you created your hosting with an earlier version, you can upgrade it directly from your hosting management, available in your Gandi account.
General Functioning¶
Your Node.js application must be composed of at least a file called server.js
, but the recommended setup is to use a package.json
file where you specify your application’s dependencies and entry point.
This entry point file will be executed by the Node.js interpreter when your web hosting is started, or after a deployment with git+SSH.
In order to receive HTTP and HTTPS requests, your application must listen on a port specified by the environment variable PORT
, available in Node.js with process.env.PORT
.
A domain name is made available for you at web hosting creation for testing purposes. In addition, you can link many domains and subdomains to your Node.js application.
Boot¶
The Web Hosting platform tries to boot your application using the following sequence:
Using a “start script” specified in
package.json
Using the default entry point defined in the
main
field inpackage.json
Use a
server.js
file, if it exists at the root of the application
Please check below for more information on each of these options.
Using package.json (Recommended)¶
The standard way to boot a Node.js application is to use settings from npm’s package.json
file. Web 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 Web 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. Web 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 Web Hosting",
"engines": {
"node": "6"
},
"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¶
The simplest way to start a Node.js application for Web Hosting is to create a file named server.js
at the root of your project. In the absence of any of the settings specified in the previous section, the web hosting will try to boot your application by running this file.
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
Note
WEB_MEMORY and WEB_CONCURRENCY values depend on your web hosting type (S, M, L, XL, XXL). The former is always set at the maximum for your web hosting type. The latter is our recommendation based on the web hosting 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 Management¶
The Node.js Web Hosting platform takes care of installing your dependencies and launching your application during the git+SSH deploy process. Simply specify the dependencies in the package.json
file at the root of your project:
package.json
{
"name": "website",
"version": "0.0.1",
"dependencies": {
"express": "3.x"
}
}
Selection of Node.js Version¶
Specify the versions you want to use in your project’s package.json file. For example:
package.json
{
"engines": {
"node": "14",
"npm": "*"
}
}
The example above will force the use of Node.js 6.x. For more information about the engines
field , see https://docs.npmjs.com/files/package.json#engines.
Check out the official Node.js website for more information about current versions versions.
Deployment Tips and Tricks¶
The postinstall
npm script can be used to build an app in the Web Hosting builder environment right after the npm install
step is completed. You can preface your postinstall
command with [ -z \"$GANDI\" ] || NODE_ENV=production
to ensure the command is only executed inside the Web Hosting builder environment, and not in the local development environment.
Note
The web hosting environment variable $GANDI
value is set to the web hosting’s hostname. You can use its value if you have multiple web hostings, e.g. for production and pre-production.
package.json
{
"scripts": {
"postinstall": "[ -z \"$GANDI\" ] || NODE_ENV=production npm run build"
}
}
Also, you can set package.json[config]
to ensure the builder runs everything with NODE_ENV=development
, which is useful for installing dependencies
+ devDependencies
for running a build process, but not if you only want to install dependencies
before running the app.
package.json
{
"config": {
"NODE_ENV": "development"
}
}
Websockets¶
Websockets is not currently supported on the Web Hosting platform.
Logs¶
The standard output and errors of your website are sent to a log file on your disk, which you can access to debug your application.
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 application’s dependencies.
Additionally, you can view the history of actions taken by the program in charge of launching your app:
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 in this file.
Database¶
MySQL¶
MySQL 5.7 (Percona) is available to use with Node.js web hostings on Web 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, as it is automatically setup when the web hosting is created.
You can create as many databases and database users 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 Web Hosting to learn more.
Below is a minimalistic Node.js code example to test the database connection on Web 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 Web Hosting",
"main": "index.js",
"engines": {
"node": "4"
},
"dependencies": {
"mysql": "*"
}
}
PostgreSQL¶
PostgreSQL version 9.6 is available for Web Hosting with Node.js.
Your web hosting’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 Web Hosting to learn more.
Below is a minimalistic Node.js code example to test the database connection on Web Hosting:
index.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 Web Hosting",
"main": "index.js",
"engines": {
"node": "4"
},
"dependencies": {
"pg": "*"
}
}