Mastering Environment Variables in PM2: A Comprehensive Guide

Mastering Environment Variables in PM2: A Comprehensive Guide

PM2 is a powerful, feature-rich process manager for applications. It provides developers with a robust set of tools to keep applications online 24/7, manage log files, and automate common tasks. One of the key features of PM2 is its ability to manage environment variables, which are crucial for configuring applications and making them adaptable to different environments.

Environment variables in PM2 can be set in various ways, including directly in the command line when starting a process, or within the PM2 configuration file, also known as the ecosystem file. These variables can be updated even while an application is running, providing flexibility and control over the application’s environment. Check How to Manage Applications with PM2 for a complete tutorial.

In the following sections, we will delve deeper into how to set, manage, and update environment variables in PM2, along with some best practices to follow.

What is the command to set an environment variable when starting a process in PM2?

Environment variables are variables that are defined outside of your application code, and can be accessed by your application at runtime. Environment variables are useful for storing configuration settings, secrets, or other information that you don’t want to hardcode in your application code, or that you want to change depending on the environment (such as development, testing, or production).

To set an environment variable when starting a process in PM2, you can use the --env option, followed by the name of the environment variable and its value. For example, to set the environment variable PORT to 3000 when starting app.js, you can run the following command:

# Set the PORT environment variable to 3000 when starting app.js
pm2 start app.js --env PORT=3000

You can also set multiple environment variables at once, by separating them with commas. For example, to set the environment variables PORT, DB_URL, and SECRET when starting app.js, you can run the following command:

# Set multiple environment variables when starting app.js
pm2 start app.js --env PORT=3000,DB_URL=mongodb://localhost:27017/mydb,SECRET=abc123

Alternatively, you can use the env option in your configuration file, and specify the environment variables as key-value pairs. For example, to set the same environment variables as above when starting app.js, you can use the following configuration file:

module.exports = {
  apps: [
    {
      script: "app.js",
      env: {
        PORT: 3000,
        DB_URL: "mongodb://localhost:27017/mydb",
        SECRET: "abc123",
      },
    },
  ],
};

Then, you can run the following command to start your application with the configuration file:

# Start app.js with the configuration file
pm2 start config.js

The advantages of setting environment variables when starting a process in PM2 are:

  • It allows you to pass and access configuration settings, secrets, or other information to your application without hardcoding them in your code.
  • It allows you to change the environment variables depending on the environment (such as development, testing, or production), by using different configuration files or commands.
  • It allows you to keep your environment variables consistent across all your processes, by using the same configuration file or command.

How to update an environment variable for a running application in PM2?

Sometimes, you may need to update an environment variable for a running application in PM2, without stopping or restarting the application. For example, you may want to change the value of a configuration setting, a secret, or a feature flag.

To update an environment variable for a running application in PM2, you can use the pm2 set command, followed by the name of the application, the name of the environment variable, and the new value. For example, to update the environment variable PORT to 4000 for the application app.js, you can run the following command:

# Update the PORT environment variable to 4000 for app.js
pm2 set app.js:PORT 4000

This command will update the environment variable in the PM2 process list, and send a SIGUSR2 signal to the application, which will trigger a reload of the environment variables. However, this command will not update the environment variable in the configuration file, so you need to manually edit the file if you want to persist the change.

The advantages of updating an environment variable for a running application in PM2 are:

  • It allows you to change the environment variables without stopping or restarting the application, which can improve the availability and responsiveness of your application.
  • It allows you to test different values of the environment variables, and see the effects on your application in real time.
  • It allows you to override the environment variables that are set in the configuration file, or the system, for a specific application.

The disadvantages of updating an environment variable for a running application in PM2 are:

  • It does not update the environment variable in the configuration file, so you need to manually edit the file if you want to persist the change.
  • It does not update the environment variable for all the processes of the application, if you are using cluster mode. You need to specify the process ID or the process name with the index to update the environment variable for a specific process. For example, to update the environment variable PORT to 4000 for the first process of app.js, you can run the following command:
# Update the PORT environment variable to 4000 for the first process of app.js
pm2 set app.js-0:PORT 4000

It does not work for some environment variables that are read only once at the start of the application, such as NODE_ENV or DEBUG. You need to restart the application to apply the change for these environment variables.

How to List All Environment Variables Set in PM2

To list all the environment variables for a specific process in PM2, you can use the pm2 env process_name_or_id command. Replace process_name_or_id with the name or ID of the process you’re interested in. This command will display all the active environment variables for the specified process. Please note that this command only shows the environment variables for the specified process. It does not show the environment variables defined in the ecosystem file that are not currently active for the process. To see these variables, you would need to look at the ecosystem file directly.

Best Practices for Managing Environment Variables in PM2?

Environment variables are an essential part of any Node.js application, as they allow you to store and access configuration settings, secrets, or other information that you don’t want to hardcode in your application code, or that you want to change depending on the environment. However, managing environment variables in PM2 can be tricky, as you need to consider the following aspects:

  • Security: You need to ensure that your environment variables are not exposed to unauthorized parties, such as hackers, competitors, or malicious users. You should avoid storing your environment variables in plain text files, such as .env or .json, or in your version control system, such as Git or SVN. You should also use encryption or hashing techniques to protect your sensitive environment variables, such as passwords, tokens, or keys.
  • Consistency: You need to ensure that your environment variables are consistent across all your processes, environments, and servers. You should use the same names, values, and formats for your environment variables, and avoid using conflicting or ambiguous names. You should also use the same configuration files or commands to set your environment variables, and avoid using different methods for different applications or environments.
  • Maintenance: You need to ensure that your environment variables are up to date and easy to maintain. You should document your environment variables and their meanings, and keep them organized and structured. You should also review your environment variables regularly, and remove any unused or obsolete ones. You should also use the PM2 commands or features to update or reload your environment variables, and avoid manually editing or restarting your processes.

Here are some best practices for managing environment variables in PM2, based on the aspects mentioned above:

  • Use the configuration file to set and manage your environment variables, as it allows you to specify the environment variables for each application, or for all applications at once, in one place. You can also use different configuration files for different environments, such as development, testing, or production, by using the --env option to specify the name of the file.
  • Use the env option in the top level of the configuration file to set the environment variables for all applications, and use the env option in each application to override or add the environment variables for a specific application. This will help you keep your environment variables consistent and organized.
  • Use the process.env object to access the environment variables in your application code, and avoid using hard-coded values or global variables. This will help you keep your application code secure and flexible.
  • Use the pm2 set command to update an environment variable for a running application, without stopping or restarting the application. This will help you change the environment variables dynamically and efficiently.
  • Use the pm2 reload command to reload your application with the updated environment variables, without losing any requests or causing any downtime. This will help you apply the changes to your environment variables gracefully and reliably.
  • Use the pm2 env command to list all the environment variables set in PM2, and their values. This will help you check and verify your environment variables easily and quickly.

Conclusions

Environment variables are an essential part of any application, as they allow you to store and access configuration settings, secrets, or other information that you don’t want to hardcode in your application code, or that you want to change depending on the environment. However, managing environment variables in PM2 can be tricky, as you need to consider the security, consistency, and maintenance aspects of your environment variables.