web developer's thoughts W.D.T.

Deploy and manage Nodejs applications with PM2

Deploy, start, stop and manage Node.js applications easily with PM2 process manager.

Prologue

In this guide I’m going to explain how to set up a deployment workflow using PM2, a popular tool used to manage and monitor Node.js application.

As prerequisites, let’s suppose you have your code up to date to a remote repository like github or bitbucket and you have access to the remote machine that will host your application.

Connect to the remote machine with an ssh key

If you are already able to do that, you can skip this section, otherwise keep reading.

In order to connect to a server with a ssh-key, first you need to create one. You can generate a new one by executing

ssh-keygen -t rsa

Leave the default name id_rsa and you can leave the passphrase blank if your main goal is just to figure out how this stuff works.

At this point a pair of keys (public and private) will be generated for you in ~/.ssh, now you need to copy your public key to the remote server, you can easily do that with

ssh-copy-id user@ipAddressOfRemoteMachine

You will be asked for the password of course and after that you will be able to access the remote machine without providing a password, but using (implicitly) your new ssh-key.

Access the code repository from the remote machine

The next step is to make sure that the code inside the repository (github, bitbucket or similar) can be accessed from the remote server through ssh-key.

In order to do that you will need to generate a new ssh key (like we did before, but inside the remote machine) and add it to the repository to allow it to be used to pull and clone: you should look for “deploy keys” inside the setting of your project page.

In this case it if necessary to manually copy-paste the key, just cat id_rsa.pub to show the content.

To check that all it’s working properly you can simply clone the project (and delete it later, this is just a test), remember to use the code>ssh option which imply to use the ssh-key and not the username/password.

Configuring PM2

At this point you should be ready to focus on PM2, first of all you need to install it globally in both your local and remote machine

npm install pm2 -g

Then in your local machine generate the PM2 config file ecosystem.config.js with

pm2 init

Now you need to change and add some parameters in order to make it works correctly

module.exports = {
    /**
     * Application configuration section
     * http://pm2.keymetrics.io/docs/usage/application-declaration/
     */
    apps: [
        {
            name: 'My - Application', // friendly name to use for your application
            script: 'index.js', // the file to execute to start the server

            env: { // variables to always use, shared
                COMMON_VARIABLE: 'true'
            },

            env_production: { // variables to set in production environment
                NODE_ENV: 'production'
            }
        },
    ],

    /**
     * Deployment section
     * http://pm2.keymetrics.io/docs/usage/deployment/
     */
    deploy: {
        production: {
            user: 'username for the remote machine',

            host: 'ip of the remote machine',

            // branch to use
            ref: 'origin/master',

            repo: 'your git repository address .git',

            // to find out, just "pwd" in the remote machine
            path: 'absolute path to working directory of the project', 
             
            // to make sure to pull the latest commit
            'pre-deploy': 'git fetch --all',

            // to execute after every deploy
            'post-deploy': 'npm install && pm2 startOrRestart ecosystem.config.js --env production'
        },
    }
};

What this file does is describe one o more applications and how to handle them.

The next step is to setup the remote machine, that can be done with a simple command (still from your local pc):

pm2 deploy production setup

This is going to create the folders structure that PM2 uses in order to perform deploys and rollbacks.

Finally you can run the actual deploy command

pm2 deploy production

This is going to perform the following actions:

Common workflow and commands

Your usual deploy workflow will consist of making changes to the code, push them to the repository and finally run the deploy command.

Of course the most basic and used commands are start, restart, stop, which do exactly what you think they do and startOrRestart is a handy shortcut as well, especially in case you don’t know if the application is already running or not.

Sometimes a new change could break your app though, in this case the rollback command comes in help:

pm2 deploy production revert 1

This goes back of one commit and restart the process, or more specifically executes the post-deploy hooks.

Another useful command is exec, it allows you to run some instructions directly in the remote machine:

pm2 deploy production exec "npm run myTask"

Another couple of common utilities are the pm2 list, which prints the list of registered application with their actual status and pm2 logs -process id-, which shows the chosen application logs.

Those are the most common and used, but there are a lot more available.

Conclusion

If you are interested in more commands or features like clusters, load balancing and more detailed informations and statistics about the running applications, please refer directly to the official documentation on PM2 to find out more.

I hope that this basic intro was helpful, don’t forget to take a look to the other posts, you may find something interesting !

Highlighted posts see all

Deploy and manage Nodejs applications with PM2

Read
see all posts