每天进步一点点:PM2设置开机自启动

in #cn5 years ago

之前的文章中,我介绍了可以使用PM2来让node.js程序一直运行,但是这样做的一个前提是我们要执行一下pm2 start xxx.js命令。


(图源 :pixabay)

那么新问题来了,每次我们需要重启服务器,都需要重新执行一下pm2 start xxx.js命令,是不是很麻烦,有没有办法让PM2在开机时自动启动我们的应用?

pm2 startup

方式之一是使用pm2 startup,大致步骤如下:

pm2 start xxx.js启动应用。
pm2 save保存
pm2 startup来设置开机自动启动。

但是因为我的PM2是本地安装的(并非全局安装),而且也不想以root用户直接运行应用,所以不去考虑这种方法。

使用rc.local

第二种方法是使用rc.local。

使用rc.local可能是相当过时的办法,但是对我而言,简单且好用就可以。

首先创建rc.local文件,并设置执行权限

sudo vi /etc/rc.local
sudo chmod u+x /etc/rc.local

在rc.local文件第一行加入如下语句

#!/bin/sh -e

否则,可能会出现类似如下错误:

之后在rc.local中添加如下内容:

su -c '~/bin/pm2 start ~/xxx/app.js' --login userxxxx

其中-, -l, --login代表:

Provide an environment similar to what the user would expect had the user logged in directly.

这样就会加载用户的环境,否则会出现类似如下错误:

/usr/bin/env: ‘node’: No such file or directory

因为在pm2的脚本中使用了如下内容:

#!/usr/bin/env node

验证

进行上述设置后,直接重启服务器,发现我们的服务访问正常,说明上述设置 无误。

需要注意的几个坑上边已经提到啦(很不幸,我都踩到了,哈哈)

相关链接


Vote For Me As Witness
https://steemit.com/~witnesses type in oflyhigh and click VOTE

Vote @oflyhigh via Steemconnect
Thank you!

Sort:  

恭喜你!您的这篇文章入选 @justyy 今日 (2019-07-14) 榜单 【优秀的文章】, 回复本条评论24小时内领赏,点赞本评论将支持 @dailychina 并增加将来您的奖赏。
@justyy 是CN区的见证人,请支持他,给他投票,或者设置justyy为见证人代理。感谢!@justyy的主要贡献:https://steemyy.com

Congratulations! This post has been selected by @justyy as today's (2019-07-14) 【Good Posts】, Steem On! Reply to this message in 24 hours to get rewards. Upvote this comment to support the @dailychina and increase your future rewards! ^_^

SteemIt 工具、API接口、机器人和教程
SteemIt Tools, Bots, APIs and Tutorial



If you believe what I am doing, please consider a spare vote voting me here, thank you very much indeed.

@justyy - the author of https://SteemYY.com and I have been a Steem Witness for more than a year now.

区块链中文第一大银行简介:你的比特币拿不了利息,但是你把比特币换成steem后就能拿利息了!

Thank you so much for participating in the Partiko Delegation Plan Round 1! We really appreciate your support! As part of the delegation benefits, we just gave you a 3.00% upvote! Together, let’s change the world!

Coin Marketplace

STEEM 0.20
TRX 0.13
JST 0.030
BTC 65527.96
ETH 3466.32
USDT 1.00
SBD 2.52