繁体   English   中英

如何通过 PM2 运行“npm start”?

[英]how to run "npm start" by PM2?

我在这里看到了很多问题,但这对我不起作用。 那为什么要问这个问题?

我正在使用 DigitalOcean Ubuntu 16.04 服务器。 我有一个由“npm start”运行的节点项目。

脚本是:

"scripts": {    
    "start": "node ./bin/www"
}

一般pm2为

pm2 start app.js

由于我的脚本是这样并且由npm start运行,我如何才能永远运行我的服务器。

你可以像这样运行内置的 npm 脚本:

pm2 start npm -- start

如果您有自定义脚本,则可以像这样运行:

pm2 start npm -- run custom

——

在您的情况下, pm2 start npm -- start将运行node ./bin/www 更改start脚本node app.js ,如果你想运行node app.js

npm start &&节点app.js有所不同。 它取决于项目的启动脚本。

在您的情况下,上述答案是正确的,它将在pm2 start npm -- start

但是,如果它也对您不起作用(我不知道为什么它对您不起作用,请与我们分享任何错误),则可以更改启动脚本。

为此,您必须在bin/www文件中更改代码,您必须将代码用于运行服务器

例:

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);


var server = http.createServer(app);



server.listen(port);
server.on('error', onError);
server.on('listening', onListening);



function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

而您在www文件上写的其他文件以运行服务器,则必须移动app.js或主文件,然后您可以尝试:

pm2 start app.js
or
forever start app.js

是的,您可以通过优雅地使用 pm2 配置 (json) 文件非常有效地完成此操作。

package.json 文件(包含以下示例脚本)

"scripts": {
    "start": "concurrently npm:server npm:dev",
    "dev": "react-scripts start",
    "build": "node ./scripts/build.js",
    "eject": "react-scripts eject",
    "lint": "eslint src server",
    "shivkumarscript": "ts-node -T -P server/tsconfig.json server/index.ts"
  }

假设我们要使用 pm2 实用程序运行名为“shivkumarscript”的脚本。 因此,我们的 pm2 配置文件应该如下所示,包含值为 'npm' 的 'script' 键和值为 'run' 的 'args' 键。 在我们的例子中,脚本名称是“shivkumarscript”。

生态系统.config.json 文件

module.exports = {
    apps: [
        {
            name: "NodeServer",
            script: "npm",
            automation: false,
            args: "run shivkumarscript",
            env: {
                NODE_ENV: "development"
            },
            env_production: {
                NODE_ENV: "production"
            }
        }
    ]
}

假设你已经在你的机器上安装了 Node.js、NPM 和 PM2。 然后下面应该是通过 pm2 启动应用程序的命令,它将依次运行 npm 脚本(在应用程序的 package.json 文件中提到的命令行):

对于生产环境:

pm2 start ecosystem.config.js --env production --only NodeServer

对于开发环境:

pm2 start ecosystem.config.js --only NodeServer

......还有Boooom! 伙计们

我的应用程序称为“app.js”。 我有一个用于快速 Node.js 应用程序的完全相同的启动脚本。

在谷歌搜索吨之后,这解决了我的问题,而不是调用 pm2 start app.js。

pm2 start ./bin/www

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM