Last Updated: October 07, 2020
·
10.28K
· yitsushi

Node.js + Node-Foreman

Node Foreman is a Node.js version of the popular Foreman tool, with a few Node specific changes.

Node Foreman

Install && Setup

First of all, we need to install globally:

$ npm install -g foreman

Go to the root of your application and create a file with name of Procfile:

web: node app.js
worker: node workers/checkmail.js
dev: node-supervisor app.js
profile: node --prof  app.js

What we did? The Procfile define applications or server processes. Now we defined a web that run the main web application, a worker to run a worker process, a dev to run our web application with node-supervisor (if a file changed node restart itself) and a profile to run the Node.js profiler on our web application.

Run

Why is it good for us? If you want to host you app on Heroku then you need this Procfile because Heroku uses the same method to run it. Now we can start our app with Node Foreman (of course you can use the original Foreman). So start our web process with one thread:

$ nf start web=1

If you want to run it with more thread to test concurrency you can change the number after the equal sign:

$ nf start web=5

If you want to run multiple process then just list process identifiers:

$ nf start web=3 worker=5

Environments

A bit (ok, not a little) annoying when your password appears in the git repository. I really hate to see build-in database connection details or username/password pairs. We can use environment variables to tell these information to our app. Foreman and Node Foreman can handle a specified file with name of .env. We can describe env variables to our app like database access information.

NODE_ENV=development
MYSQL_HOST=localhost
MYSQL_DATABASE=Database Name
MYSQL_USER=MySQL Username
MYSQL_PASSWORD=MySQL Password
MONGO_URL=mongodb://localhost/indexer
REDIS_URL=redis://rediscloud:password@host:port

Now when we run our app with nf start web=1 then the app can reach these variables with process.env.VARIABLE_NAME. So we can turn on logging in development mode or turn off in production mode with process.env.NODE_ENV. Foreman define a PORT variable so you need to change the listen port in your code to process.env.PORT || 3000. Add this file into your .gitignore and create a new one on production servers. Each workstation has its own configuration.

If you like (as me), you can use json format in your .env file:

{
  "node": {
    "env": "development"
  },
  "mysql": {
    "host": "localhost",
    "database": "Database Name",
    "user": "MySQL Username",
    "password": "MySQL Password",
  },
  "mongo": {
    "url": "mongodb://localhost/indexer"
  },
  "redis": {
    "url": "redis://rediscloud:password@host:port"
  }
}