[英]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) 文件非常有效地完成此操作。
"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”。
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.