What is the best way to provide execution arguments to an app through PM2?

While attempting to start my app using pm2, I encountered an issue with passing arguments. Despite using the command pm2 start app.js -- dev, I was unable to pass the argument successfully. Interestingly, this worked without any issues when using forever.

Answer №1

To execute node arguments through the CLI, use this command:

pm2 start myServer.js --node-args="--production --port=1337"

Updated Version

You have the flexibility to include any arguments after --

pm2 start app.js -- --prod --second-arg --third-arg

For more information on deployments, refer to the Sails documentation on deployment.

Answer №2

If you're looking for a solution, you can follow the instructions provided in this ticket: https://github.com/Unitech/pm2/issues/13

Consider using environment variables when passing the environment configuration. By creating a variable accessible by any process within that environment with process.env.*.

For example, let's say you have a configuration file called config.json:

{
   "dev": {
        "db": {
            "hosts":["localhost"],
            "database": "api"
        },
        "redis": {
            "hosts": ["localhost"]
        }
   },
   ...
}

To import your config:

var config = require('./config.json')[process.env.NODE_ENV || 'dev'];

db.connect(config.db.hosts, config.db.database);

You can set the variable in your environment through the shell:

export NODE_ENV=staging
pm2 start app.js

The environment variable will persist throughout your session. To make it last beyond the session, modify the ~/.bashrc file accordingly. PM2 offers a deploy system, enabling you to set environment variables before daemonizing your app. This practice is commonly used in POSIX systems to retain parameters across processes.

Additionally, consider stop/starting locally and restarting (if in cluster mode) as needed to minimize downtime in production.

Answer №3

Defining arguments within a process is achievable.

To create a new process in the `ecosystem.config.js` file, include an `args` key as shown below:

{
  name            : 'my-service',
  script          : './src/service.js',
  args            : 'firstArg secondArg',
},
{
  name            : 'my-service-alternate',
  script          : './src/service.js',
  args            : 'altFirstArg altSecondArg',
}

In this setup, both processes utilize the same file (`service.js`) but pass different sets of arguments to it.

It's important to note that handling these arguments should be done within the `service.js` file. For instance, using `process.argv[2]` retrieves the first argument and so forth in my scenario.

Answer №4

After conducting thorough testing on my Windows machine, I can confirm that the solution below successfully allows for passing arguments to a Node.js application using pm2.

** There are two types of arguments:

  1. node-args - to be used before npm start
  2. args - to be used within your node program

There are two methods to pass arguments with pm2.

Option 1: passing arguments via pm2 commands.

Option 2: utilizing a config file such as ecosystem.config.js

Option 1 (Passing args through commands):

pm2 start app/myapp1.js --node-args="--max-http-header-size=80000" -- arg1 arg2
//To access the arguments in your node program:
console.log(process.argv[2]); // arg1
console.log(process.argv[3]); // arg2

Option 2 (Using a config file): If you are utilizing ecosystem.config.js, you can define the configuration as follows:

    {
      name: 'my-app',
      script: 'app\\myapp1.js',
      env: {
        NODE_ENV: 'DEV',
        PORT : 5051
      },
      node_args: '--max-http-header-size=80000',
      args : 'arg1 arg2',
      instances: 1,
      exec_mode: 'fork'
    }

To begin in dev mode:

pm2 start --name myapp  app/myapp1.js -- .\ecosystem.config.js

To start in production mode, simply add --env=production

pm2 start --name myapp  app/myapp1.js -- .\ecosystem.config.js --env=production 
//To access the arguments in your node program:
console.log(process.argv[2]); // arg1
console.log(process.argv[3]); // arg2

Answer №5

To send parameters to your script, simply add them after --. Here's an example:

pm2 start app.js -i max -- -a 23 // Remember to pass arguments after the -- to app.js!

Answer №6

When it comes to running Python scripts in a Linux environment, I always rely on PM2. If you have a script with a single parameter that needs to run continuously at set intervals, you can use the following command:

pm2 start <filename.py> --name <nameForJob> --interpreter <InterpreterName> --restart-delay <timeinMilliseconds> -- <param1> <param2>

filename.py represents the name of the Python script that will be executed using PM2
nameForJob should be a meaningful identifier for the job being performed
InterpreterName refers to the Python interpreter used to run the script, typically 'python3' in a Linux environment
timeinMilliseconds denotes the time interval before the script is rerun
param1 and param2 are parameters required by the script.

Answer №7

There are two methods to pass parameters from pm2 to nodejs in CLI:

  • pm2 start app.js -- dev --port=1234 (be sure to include an extra space between -- and dev)
  • pm2 start app.js --node-args="dev --port=1234"

Using either of these approaches, you will find the values in process.argv as follows: ['dev','--port=1234']

Answer №8

To specify arguments for a node, you can simply do the following:

NODE_TLS_REJECT_UNAUTHORIZED=0 NODE_ENV=dev pm2 start server.js --name web-server

Answer №9

I must add on to the responses provided regarding npm scripts

Regarding npm scripts

// package.json
{
  "scripts": {
    "start": "pm2 start --node-args=\"-r dotenv/config\" index.js"
  }
}

npm run start initiates pm2 start for index.js with additional node-args -r dotenv/config that includes environment variables from a .env file using dotenv

Answer №10

Explained in the pm2 documentation

//Activate settings for production environment
$ pm2 start app.js --env production 

//Apply settings for staging environment
$ pm2 restart app.js --env staging

Answer №11

To initiate pm2, use the following command: pm2 launch app.js --name "app_name" -- arg1 arg2

In your script, retrieve the arguments like so: console.log(process.argv);

The process.argv variable contains an array with the following elements: [ '/usr/local/bin/node', '/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js', 'arg1', 'arg2' ]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Upon a successful AJAX post request, the page fails to display

I'm encountering an issue connecting my front-end JavaScript to my back-end Node/Express. Although the requests from my client-side js to the server return successful, the page I am requesting fails to render. On the server side, here is my code: ap ...

What is the best way to display all MongoDb records when there is no query specified?

Seeking advice on modifying an endpoint that currently fetches all courses from the database by default. I am looking to update it so that when req.query.class is empty, it retrieves all records, otherwise returns records conditionally. router.get('/a ...

Dealing with null values in foreign keys using Sequelize

I am currently working on a form that takes input from a web page and is handled with sequelize. The foreignKey is set using a select form, so if the user doesn't make a selection, I want to return a constraint/validation error with the message "is re ...

Troubleshooting problems with querying in mongoose and express: A comprehensive guide

As someone who is still relatively new to dynamic routing, I am struggling with implementing it correctly. My goal is to create a function that retrieves the user's purchases from the database and exports it as a CSV file. Everything was working fine ...

Upon completion of the user registration process, the req.isAuthenticated method is showing a false

I've encountered this issue in a few of my previous apps and I'm unsure what's causing it. When I navigate to the login page and successfully log in a user, everything works as expected and I have access to the logged-in user. However, when ...

There is no 'Access-Control-Allow-Origin' header found on the requested resource in Node.js

I'm currently facing an issue with basic auth while trying to log in to my Grafana page using Node.js and express. I keep receiving an error message like the one shown below.https://i.stack.imgur.com/vRMOF.png My setup includes 'localhost:4000&a ...

Struggling to add content to user blogs with mongoose, not functioning as expected

database.js import mongoose from "mongoose"; const UserSchema=new mongoose.Schema({ _id:mongoose.Types.ObjectId, name:{ type:String, require:true }, email:{ type:String, require:true }, pas ...

Error: npm version not recognized. The specified path could not be located

After downloading Node.js for Windows 7 from https://nodejs.org/en/download/, I encountered an issue. When I run node -v, the output shows v8.9.4. However, checking npm -v returns the following error: The system cannot find the path specified. 5.6.0 The ...

Is it possible that using npm link could be the root cause of the "module not

As I delve into understanding how to utilize TypeScript modules in plain JavaScript projects, it appears that I am facing a limitation when it comes to using npm linked modules. Specifically, I can successfully use a module that is npm-linked, such as &apo ...

Using npm start to launch the Node application within a Docker container presents a challenge

I have come across various Docker and Node.js Best Practices articles, including resources like this one, 10 best practices to containerize Node.js web applications with Docker, and Dockerfile good practices for Node and NPM. Most of these articles were pu ...

Exploring a single collection through multiple searches within a single query

I am facing a challenge with using an array of values as search queries in my code. I need to query a collection based on multiple values from the array, but I am unsure how to efficiently achieve this without running into any issues. Here is an example of ...

the architecture of multi-tenancy using Node.js and Sequelize

Currently, I am designing a multi-tenant application using nodejs and sequelize with the MySQL dialect. The plan is to have a single application that connects to multiple databases, each designated for a specific client. After authentication (using passp ...

Issue with Node 16: npm refusing to accept a trusted self-signed certificate

When attempting to run npm install while behind a proxy that intercepts HTTPS connections with a custom CA certificate, there was an issue. This occurred while using Node 16. Each time the command is executed, it fails with the following error: 3023 error ...

Server receives an empty req.body from Axios GET request

I've been encountering an issue in my React app where Axios sends an empty request body when making a GET request. Interestingly, I have successfully made requests using Insomnia without any problems on the backend. I've attempted a few solutions ...

Retrieving documents in Mongoose by searching for nested object IDs will return the complete document

This is the structure of my document: { "_id": "590dc8b17e52f139648b9b94", "parent": [ { "_id": "590dc8b17e52f139648b9b95", "child": [ { "_id": "590dc8b17e52f139648b9b8f" }, { ...

Tips for circumventing the Sails body parser when dealing with multi-part form uploads

I'm encountering an issue on Sails.js (0.9.16) with POST requests being sent from a JAVA client. I have constructed a POST request on the client side (using enctype: multipart/form-data) to send a text file. On the server side, I've created a co ...

Unable to verify credentials for accessing the MongoDB database on localhost

Recently, I embarked on a new project using Express and decided to utilize MongoDB as my database due to Node.js being the backend technology. This is my first time working with Mongo, and although I can authenticate successfully from the terminal, I' ...

Is there a method to display logs in Node JS without relying on process.stdout.write?

I am currently experimenting with piping two Node.js scripts together, and I have found that it works well when using the following method. How to pipe Node.js scripts together using Unix | pipe (on the command line)? For example: $ ./script1.js | ./scr ...

Having trouble establishing a connection between my Node.js app and Redis OM

I am currently attempting to establish a connection with a Redis cloud database. The documentation provides the following code snippet: import { createClient } from 'redis' import { Client } from 'redis-om' (async function() { let r ...

Building an application using NodeJs and Express, where the response is triggered after an

As a Java developer looking to organize my code, I've split it into Routes and Services. Note: While I may not be an expert in Node.js. Service Code: UserService.prototype.findUser = function(userId) { var self = this; container.db.users.findOn ...