一、在docker中pm2守护多个进程的方法:
方法一 :使用pm2-runtime可以
如何在docker里面同时启动多个pm2进程_祥仔先生的博客-CSDN博客_pm2-docker
方法二:pm2 启动的时候使用--no-daemon
如果在docker中需要记录pm2的日志到文件中,推荐使用下面的方法来启动服务
例如:
#!/bin/bash
pm2 start ./build/server.js --name app; pm2 start ./build/bin/crontab.js --name crontab --no-daemon
二、日志记录
坑一: 首先我们来说一下坑,就是pm2-runtime默认是不记录日志到文件的。
commander.version(pkg.version)
.....
.option('--error <path>', 'error log file destination (default disabled)', '/dev/null')
.option('--output <path>', 'output log file destination (default disabled)', '/dev/null')
....
所以在使用pm2-runtime启动项目的时候默认是不生成日志的。这个是需要注意的,需要自己指定。
坑二:如果我们在docker中打开了pm2的日志就需要考虑到,随着时间的推移日志的量会越来越大,可能会导致docker镜像的空间被占满。这里面就需要引入pm2-logrotate
1、安装pm2-logrotate的前提是pm2已经安装了
2、其次默认的日志一般会存放在/root/.pm2/logs下
DockerFile中可以添加如下的配置:
RUN npm i pm2 -g
RUN pm2 install pm2-logrotate
RUN pm2 set pm2-logrotate:retain 15 && \
pm2 set pm2-logrotate:max_size 300M && \
pm2 set pm2-logrotate:compress true
配置说明
max_size
(Defaults to10M
): When a file size becomes higher than this value it will rotate it (its possible that the worker check the file after it actually pass the limit) . You can specify the unit at then end:10G
,10M
,10K
- 配置项默认是 10MB,并不意味着切割出来的日志文件大小一定就是 10MB,而是检查时发现日志文件大小达到 max_size,则触发日志切割。
retain
(Defaults to30
file logs): This number is the number of rotated logs that are keep at any one time, it means that if you have retain = 7 you will have at most 7 rotated logs and your current one.- 这个数字是在任何一个时间保留已分割的日志的数量,这意味着如果您保留7个,那么您将最多有7个已分割日志和您当前的一个
compress
(Defaults tofalse
): Enable compression via gzip for all rotated logs- 对所有已分割的日志启用 gzip 压缩
dateFormat
(Defaults toYYYY-MM-DD_HH-mm-ss
) : Format of the data used the name the file of log- 文件名格式化的规则
rotateModule
(Defaults totrue
) : Rotate the log of pm2's module like other apps- 像其他应用程序一样分割 pm2模块的日志
workerInterval
(Defaults to30
in secs) : You can control at which interval the worker is checking the log's size (minimum is1
)- 您可以控制工作线程检查日志大小的间隔(最小值为
1
)单位为秒(控制模块检查log日志大小的循环时间,默认30s检查一次)
- 您可以控制工作线程检查日志大小的间隔(最小值为
rotateInterval
(Defaults to0 0 * * *
everyday at midnight): This cron is used to a force rotate when executed. We are using node-schedule to schedule cron, so all valid cron for node-schedule is valid cron for this option. Cron style :- 多久备份一次
* * * * * *
┬ ┬ ┬ ┬ ┬ ┬
│ │ │ │ │ |
│ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun)
│ │ │ │ └───── month (1 - 12)
│ │ │ └────────── day of month (1 - 31)
│ │ └─────────────── hour (0 - 23)
│ └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)
复制代码
TZ
(Defaults to system time): This is the standard tz database timezone used to offset the log file saved. For instance, a value ofEtc/GMT+1
, with an hourly log, will save a file at hour14
GMT with hour13
(GMT+1) in the log name.- 时区(默认为系统时区)