How To Set Up a Node.js Application for Production with pm2, nginx

Tram Ho

Preamble

This article I write with the purpose to synthesize knowledge and supplement server-related techniques for myself. In fact, there are many ways to deploy nodejs (express framework) applications, but in this presentation I will choose stack capistrano + pm2 + nginx

Init project

To quickly use the express-generator to init project as follows:

Reference: https://expressjs.com/en/starter/generator.html .

After you have successfully initiated and started the application, the next step is to install the capistrano for automatically deploy code on the server.

Capistrano (local side)

Prerequisite

First you need to install ruby ​​(rbenv or rvm). You can then init Gemfile using the command bundle init

Edit Gemfile as below, then run bundle install to install gem.

Generate file config with command $ cap install . In Capfile uncomment the line below

The next thing is to edit the config/deploy.rb file

Depends on the environment (in this case, production). Open the file config / deploy / production.rb

EC2 (server side)

Prerequisite

The following packages need to be installed

  • Nginx

  • Node (& yarn or npm)

Install nvm

Edit the .bashrc file as shown below, then run the command source .bashrc

Final

  • PM2

App preparation

You need to create a directory with the following path /var/www/nodejs_skeleton . Directory permissions:

In the nodejs_sk skeleton directory create the following directory to prepare for deployment using the capistrano

Configuration

Nginx

Create a config file as follows: sudo vi /etc/nginx/conf.d/nodejs_skeleton.conf

Next, you need to edit the nginx.config file sudo vi /etc/nginx/nginx.conf

Check that the nginx file is working correctly

Nginx’s start / stop / restart service command is as follows

PM2

Create a client_deploy directory and then create a config file for PM2 as below (or put it in a shared folder) with cluster 2 instance

Init.d Script

  • Create a script named nodejs_skeleton as below in /etc/init.d/nodejs_skeleton nodejs_skeleton
  • Authorization: sudo chmod 755 /etc/init.d/nodejs_skeleton

Commands

Like webserver commands like nginx. When failing, you can stop / start or restart.

  • Start PM2

  • Stop PM2

  • Restart PM2

  • Check Status

Deploy

Share the news now

Source : Viblo