How to Enable PM2 to Auto Start Node.js App at System Boot?


Introduction

PM2 is a process manager for Node.js applications. It is capable of automatically restarting an application when it crashes, managing multiple applications at once, and providing detailed logs and error information. This tool has been widely adopted by Node.js developers due to its ease of use and powerful features.

One of the most significant benefits of using PM2 is that it simplifies the management of Node.js applications by automating common tasks such as starting, stopping, and restarting processes. PM2 also provides monitoring capabilities that allow developers to track application performance metrics in real-time.

The Importance of Auto Starting a Node.js App at System Boot

Node.js has become one of the most popular programming languages for developing server-side applications. These applications are often run on servers that need to be restarted frequently for updates or system maintenance.

Installing PM2

PM2 is a process manager for Node.js applications. It provides features like cluster mode, load balancing, and auto-restart on crashes. Installing PM2 is simple and straightforward, and it can be easily done using npm.

To install PM2, you need to have Node.js already installed on your machine. You can check if Node.js is installed by running the command `node -v` in your terminal.

If it's not installed, download and install it from the official website. Once you have Node.js installed, open your terminal and run the following command to install PM2 globally −

npm install pm2 -g 

This will install PM2 on your system globally so that you can use it anywhere in your system.

Step-by-step guide to installing PM2

Now that you have installed PM2 on your system, let’s go through a step-by-step guide on how to set up a Node.js application with PM2 −

  • Navigate to the directory where your Node.js application is located.

cd /path/to/your/nodejs/app 
  • Start the application with PM2 using the following command −

pm2 start app.js 

This will start your application with default settings.

  • Check if the application started successfully with this command −

pm2 list 

This will display a list of all applications running under PM2.

Configuring PM for Node.js app

PM can be configured according to specific requirements of an application. One of its main configuration options is environment variables which allows developers to specify global parameters such as database URL or authentication credentials.

To configure environment variables for an app’s ecosystem file (ecosystem.config.json), add them as key-value pairs to the “env” object. For example, to set a database URL and authentication credentials for an app, the ecosystem file should look like this −

{ 
"apps": [ { "name": "myapp", 
"script": "app.js", "env": { 
"DATABASE_URL": "", "AUTHENTICATION_CREDENTIALS": "" } } ] } 

With this configuration, the environment variables can be accessed in the code using `process.env.DATABASE_URL` and `process.env.AUTHENTICATION_CREDENTIALS`. In addition to environment variables, PM2 offers many other configuration options such as load balancing, cluster mode etc.

Enabling Auto Start at System Boot

If you are running a Node.js app that is critical for your business operations, it is essential to ensure that it starts automatically whenever the server boots up. This way, you don't have to manually start the application every time the system restarts. In this section, we will discuss how to enable auto start at system boot using different tools on various operating systems.

Understanding the process of enabling auto start at system boot

Before we dive into specific tools and methods, let's understand the general process of enabling auto start at system boot. The concept is similar across most operating systems; however, there might be variations in terms of tools and commands used.

  • Create a script file that launches your Node.js app.

  • Ensure that this script file has executable permissions.

  • Add this script file to an appropriate location in your operating system.

  • Create a service or task that runs your script file on startup.

Using systemd to enable auto start on Linux systems

Systemd is a Linux-based init system and service manager that enables users to manage services efficiently. It comes pre-installed on most modern Linux distributions like Ubuntu 16.04 and later versions.

To enable auto-start for your Node.js app with systemd −

  • Create a new file in `/etc/systemd/system` directory with `.service` extension (e.g., myapp.service).

  • Add the following configuration lines −

[Unit] 

Description=My Node.js App After=network.target 
[Service] Environment=NODE_ENV=production 
ExecStart=/usr/bin/node /path/to/your/app.js Restart=always 
User=nobody Group=nobody 
[Install] WantedBy=multi-user.target
  • Save and close the file.

  • Reload systemd configuration using the command `systemctl daemon-reload`.

  • Enable the service to start automatically at system boot with `systemctl enable myapp.service`.

Advanced Configuration Options

The Power of PM2 Advanced Configuration Options

While the basic installation and configuration of PM2 for auto-starting Node.js apps is straightforward, there are a wealth of advanced configuration options available that can help you fine-tune your setup to meet your specific needs. One powerful option offered by PM2 is the ability to customize startup scripts.

By default, PM2 will automatically detect and start Node.js applications in your home directory or current working directory. However, you can specify a custom startup script that executes any command you need to run before launching your Node.js app.

This might include things like setting environment variables, loading configuration files, or running other processes required by your application. Another useful feature offered by PM2 is the ability to set custom environment variables.

Environment variables allow you to pass important information into your application at runtime that can affect how it behaves or what data it handles. By default, PM2 will inherit all environment variables set in your shell session when starting an application.

Customizing Startup Scripts and Environment Variables with Examples

One example use case for customizing startup scripts might be running a pre-launch script that checks whether any updates are available from a Git repository before starting the main Node.js app process. To do this with PM2, we would first create a new `.sh` script file in our `~/scripts/` directory −

#!/bin/bash 
cd /path/to/my/app 
git fetch && git merge origin/master 

Then we would add an entry to our `ecosystem.config.js` file for our application that specifies this script as the `pre` command −

javascript module.exports = { 
apps: [ { name: "my-app", 
script: "/path/to/my/app/index.js", env_production: { 
NODE_ENV: "production" }, // Add the following `pre` property 
pre: "/home/myuser/scripts/update-app.sh", } ] } 

Now, every time we start our Node.js app process with PM2, it will first run this custom script to fetch any updates from our Git repository.

As for setting environment variables with PM2, suppose we need to set a custom `PORT` variable in our application based on whether we're running in development or production mode. We can achieve this by adding an entry to our application configuration file that sets the environment variable within the `env` object −

javascript module.exports = { 
apps: [ { name: "my-app", 
script: "/path/to/my/app/index.js", env_production: { 
NODE_ENV: "production" // Set custom PORT variable here: 
PORT: 8080, }, } ] } 

Now when we start our app process in production mode, it will automatically use the `8080` port specified in our configuration file.

Conclusion

Enabling autostart for Node.js apps using PM2 is a crucial step in ensuring that your application remains available and active even after system reboots. By following the steps outlined in this article, you can easily configure your PM2 to enable auto start at system boot on Linux, macOS, or Windows systems.

Updated on: 08-Jun-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements