Search code examples
nestjspm2

Nestjs with pm2, port still be used after killing the process with pm2 stop?


I deployed my Nest.js application on my VPS (Ubuntu 20.04 DO) using pm2 as process manager. Here is my step by step when I'm updating the app.

$ pm2 stop 1
$ kill -9 $(sudo lsof -t -i:4040)
$ npm run build
$ pm2 start 1

Notice that I must kill the port that the app use before I proceed to the build one, how to simplify it and become like these :

$ npm run build
$ pm2 reload 1

So I can deploy my Nest.js app gracefully and achieve at least only 1% downtime


Solution

  • Stop command keeps the app in the apps list while the delete command not.

    I think you want something like

    start.sh

    #!/bin/bash
    source .env
    ENVIRONMENT="$NODE_ENV"
    npm run build || exit
    pm2 delete "$ENVIRONMENT"
    pm2 start "npm run start:prod" --name "$ENVIRONMENT" --log-date-format 'DD-MM HH:mm:ss.SSS'
    

    If you are not using different environments, an equivalent script would be

    #!/bin/bash
    npm run build || exit
    pm2 delete my_application
    pm2 start "npm run start:prod" --name my_application --log-date-format 'DD-MM HH:mm:ss.SSS'
    

    Emitting the --log-date-format is perfectly fine. However, I have included it because I suspect it might become helpful when finding bugs in production down the line.