在Ubuntu系统上,结合Node.js生态工具可实现应用部署、进程管理、监控告警、日志分析等自动化运维任务,提升系统可靠性和运维效率。以下是具体实现方案:
在Ubuntu上安装Node.js和npm(Node.js包管理器),为后续工具使用奠定基础:
sudo apt update
sudo apt install -y nodejs npm
# 验证安装
node -v # 查看Node.js版本
npm -v # 查看npm版本
PM2是Node.js生态中最流行的进程管理器,可实现应用自动重启、负载均衡、日志管理、监控等功能,是自动化运维的核心工具。
sudo npm install -g pm2
app.js),并命名为my-app:pm2 start app.js --name "my-app"
pm2 listpm2 stop my-apppm2 restart my-apppm2 logs my-apppm2 monitpm2 startup systemd # 生成开机自启命令
sudo su -c "pm2 save" # 保存当前进程列表
通过CI/CD工具(如GitHub Actions、Jenkins)实现代码提交后自动构建、测试、部署,减少人工干预。
.github/workflows/deploy.yml文件,配置如下:name: Deploy Node.js App
on:
push:
branches:
- main # 当main分支有推送时触发
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '18' # 指定Node.js版本
- name: Install dependencies
run: npm install
- name: Build project
run: npm run build # 假设项目有build脚本
- name: Deploy to server
env:
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }} # GitHub Secrets中配置服务器SSH私钥
SERVER_USER: "ubuntu" # 服务器用户名
SERVER_HOST: "your-server-ip" # 服务器IP
DEPLOY_PATH: "/var/www/my-app" # 服务器部署目录
run: |
scp -o StrictHostKeyChecking=no -r ./dist ${SERVER_USER}@${SERVER_HOST}:${DEPLOY_PATH} # 传输构建产物
ssh ${SERVER_USER}@${SERVER_HOST} "cd ${DEPLOY_PATH} && pm2 restart my-app" # 重启应用
Jenkinsfile定义流水线,包含Build(安装依赖、构建项目)和Deploy(传输文件到服务器并重启应用)阶段。通过PM2内置监控或第三方工具(如Prometheus+Grafana)实现对应用状态的实时监控和异常告警。
pm2 list(显示进程ID、状态、内存占用等)pm2 monit(图形化界面展示CPU、内存占用)prom-client库,暴露指标端点(如HTTP请求耗时、错误率):const promClient = require('prom-client');
const httpRequestDuration = new promClient.Histogram({
name: 'http_request_duration_ms',
help: 'HTTP request duration in milliseconds',
labelNames: ['method', 'route', 'code'],
buckets: [0.1, 5, 15, 50, 100, 200, 300, 400, 500] // 指标桶
});
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
httpRequestDuration.observe({
method: req.method,
route: req.route ? req.route.path : req.path,
code: res.statusCode
}, Date.now() - start);
});
next();
});
通过结构化日志和日志分析工具(如ELK Stack、Winston)实现日志的集中存储、检索和分析,快速定位问题。
winston库记录JSON格式日志,区分错误、警告、信息等级别:const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }), // 错误日志
new winston.transports.File({ filename: 'combined.log' }), // 所有日志
new winston.transports.Console({ format: winston.format.simple() }) // 控制台输出(开发环境)
]
});
// 使用示例
logger.info('Application started', { port: 3000 });
logger.error('Database connection failed', { error: err.message });
winston-daily-rotate-file插件防止日志文件过大,自动按日期归档:const DailyRotateFile = require('winston-daily-rotate-file');
const transport = new DailyRotateFile({
filename: 'application-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true, // 压缩归档
maxSize: '20m', // 单个文件最大20MB
maxFiles: '14d' // 保留14天
});
logger.add(transport);
使用Node.js定时任务库(如node-cron)或系统Cron实现周期性自动化任务(如数据备份、报表生成)。
node-cron库,编写定时任务脚本(如每天凌晨1点清理临时文件):const cron = require('node-cron');
const fs = require('fs-extra');
// 每天凌晨1点执行
cron.schedule('0 1 * * *', async () => {
try {
await fs.emptyDir('/tmp/my-app'); // 清空/tmp/my-app目录
console.log('Temporary files cleaned up');
} catch (err) {
console.error('Cleanup failed:', err);
}
});
crontab -e),添加Cron作业(如每小时运行Node.js脚本):0 * * * * /usr/bin/node /path/to/your/script.js >> /var/log/script.log 2>&1
通过以上方案,可在Ubuntu上构建完整的Node.js自动化运维体系,覆盖从环境部署到运行监控的全生命周期,提升运维效率和系统可靠性。