PM2 Script Not Found for bin/www

Viewed 10565

Recently i decided to run my app with pm2 as a service. For me pm2 start app.mjs runs the app as a service but it seems pm2 doesn't run my express application correctly. I used express npm to build an app like this:

//Imports
import express from "express";

//Setups
const app = express();
const port = process.env.PORT;

app.get("/", async (req, res) => {
  res.send("Hello world!");
});

//Running server
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Also tried pm2 start ./bin/www that gives me an Script not found error and it seems to be okay with express-generator not the express npm alongside an app. App works correctly in dev mode (node app.mjs).

UPDATE

I solved the problem with help of Konstantinos Lamogiannis. After setup the config file as well as the answer, i changed my app.mjs to app.js form and changed the import style to const variable = require(""); and it fixed my problem. I don't know why that happened but it seems the pm2 npm may confilct with new nodejs feature which supports the import ES6 syntax.

pm2 log was giving to me this error: unhandledRejection you may have forgotten to catch a Promise rejection !

1 Answers

You can try creating a file with name: ecosystem.config.js in your projects root folder and then add the following code in the file:

module.exports = {
  apps: [{
    name: 'yourAppName',
    script: 'bin/www/app.mjs', // the path of the script you want to execute,
    // Options reference: https://pm2.keymetrics.io/docs/usage/application-declaration/
    instances: 1,
    autorestart: true,
    watch: false,
    error_file: 'err.log',
    out_file: 'out.log',
    log_file: 'combined.log',
    time: true,
    env: {
    },
  }],
};

In the config above you will notice that in script property its value is bin/www/app.mjs. I assume that you have app.mjs under bin/www directory and placed that value.

Then run pm2-runtime start ecosystem.config.js

EDIT #1

Assuming that your startup file is in your project's root directory use script: 'app.mjs'.

So your final ecosystem.config.js will be:

module.exports = {
  apps: [{
    name: 'yourAppName',
    script: 'app.mjs', // the path of the script you want to execute,
    // Options reference: https://pm2.keymetrics.io/docs/usage/application-declaration/
    instances: 1,
    autorestart: true,
    watch: false,
    error_file: 'err.log',
    out_file: 'out.log',
    log_file: 'combined.log',
    time: true,
    env: {
    },
  }],
};

Try then pm2-runtime start ecosystem.config.js from your root's project directory (where app.mjs is located).

Related