hanki.dev

Run Node app on your local machine, in the background

In my last post I wrote how to run a Telegram bot on Fly.io. This is cool and all, but sometimes you don't need your Node.js app to run 24/7. Instead, running it only when your laptop/desktop is on might be enough for many cases.

Running Node apps using pm2 is super easy; it's lightweight, runs smoothly in the background and requires almost no setup at all:

  1. Install pm2: npm install pm2 -g
  2. Start your Node app with pm2: pm2 start index.js --name my-app
  3. Generate a startup script: pm2 startup
  4. Save the app list to be restored at reboot: pm2 save

Some useful commands

  • List your current apps: pm2 list
  • View app logs: pm2 logs my-app
  • Run app with environment variables: ENV_VAR=xxx pm2 start index.js
    • Change environment variable: ENV_VAR=xxx pm2 restart my-app --update-env

#javascript

- 3 toasts