How to deploy with pm2 Javascript applications

Today I talk with you about how to deploy with pm2. I want to present a simple example for a node.js app, but you can use it to deploy react, Vue or other Javascript apps.

I know how frustrating is for some of you this part about DevOps. That’s why pm2 comes to throw us like an angel which wants to save humanity in front of the Continous Deployment process.

Pm2 configuration file

{
  "apps": [{
    "name": "App",
    "script": "./app.js",

    "autorestart": true,
    "watch": false,
    "max_memory_restart": "1G",
    "env": {
      "NODE_ENV": "development",
    },
    "env_production": {
      "NODE_ENV": "production",
    }
  }],

  "deploy": {
    "development": {
      "user": "user",
      "host": "111.111.111.111",
      "ref": "origin/develop",
      "repo": "git clone git@github.com:repo.git",
      "path": "/var/www/development",
      "post-deploy": "cd /var/www/development && npm install && pm2 reload ecosystem.json"
    },
    "production": {
      "user": "user",
      "host": "222.222.222.222",
      "ref": "origin/develop",
      "repo": "git clone git@github.com:repo.git",
      "path": "/var/www/production",
      "post-deploy": "cd /var/www/production && npm install && pm2 reload ecosystem.json --env production"
    }
  }
}

If you want to know everything about how to deploy with the pm2 process, read the official documentation.

Firstly, please add the previous configuration to your ecosystem.json file. Please make sure to fill in the details under deploy property for the environment that you are interested in. You must change the host with your own IP, repo is the ssh git remote URL of your repository, the path is the folder full path for the folder where your app is stored, and please make sure that you update the path in post-deploy as well.

How to setup ssh key

Before to move forward with the deploy process, you need one more step. You have to create an ssh key that marks your computer as trusted on the hosting server. If you don’t know how to do it, I invite you to my post about how to Generate a new SSH key and add it to the ssh-agent.

!!!The next commands are executed from your local machine, not on your remote hosting server.

After this configuration run, pm2 deploy development setup for the first time. After that, each time when you want to deploy with pm2, execute pm2 deploy development.

You can take a look at my previous post about How to deploy Node.js app with PM2 in production, where I present how to run a Typescript project in production using pm2 with ts-node plugin.

1 thought on “How to deploy with pm2 Javascript applications

Leave a Reply

Your email address will not be published.