在 Docker 环境中运行和监测 Moleculer 微服务
以下是完整的 Docker 化方案,包含运行、监测和可视化:
1. 项目结构
1 | moleculer-demo/ |
2. 修改 index.js 支持 Docker 环境
1 | const { ServiceBroker } = require("moleculer"); |
3. Dockerfile
1 | # 使用 Node.js 官方镜像 |
4. docker-compose.yml
1 | version: '3.8' |
5. prometheus.yml 配置
1 | global: |
6. 更新网关服务支持指标端点
1 | // gateway.service.js |
7. 构建和运行
1 | # 启动所有服务 |
8. 访问服务
- API 网关: http://localhost:3000
GET /api/math/add?a=5&b=3
GET /api/welcome/John
9. 监控系统访问
Prometheus:
- URL: http://localhost:9090
- 查看指标:
moleculer_actions_active_requests
Grafana:
- URL: http://localhost:3001
- 用户名:
admin
- 密码:
admin
- 添加 Prometheus 数据源:
http://prometheus:9090
- 导入 Moleculer 仪表板:
- ID:
11602
(官方仪表板) - 或从 Moleculer 指标仪表板 导入
- ID:
Jaeger 分布式追踪:
- URL: http://localhost:16686
- 查看服务调用链
10. 关键监控指标
Moleculer 自动暴露的 Prometheus 指标:
moleculer_actions_active_requests
: 当前活跃请求数moleculer_actions_time
: 请求处理时间moleculer_events_total
: 事件总数moleculer_requests_total
: 请求总数moleculer_errors_total
: 错误总数process_cpu_usage
: CPU 使用率process_memory_usage
: 内存使用量
11. 生产环境建议
健康检查:
1
2
3
4
5
6# docker-compose.yml
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 5s
retries: 3日志管理:
1
2
3
4
5
6# docker-compose.yml
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"集群部署:
1
2# 扩展服务实例
docker-compose up -d --scale app=3使用环境变量配置:
1
2
3
4
5# .env 文件
TRANSPORTER=nats://nats:4222
METRICS_PORT=3030
TRACING_ENABLED=true
TRACING_EXPORTER=Jaeger
12. 常用诊断命令
1 | # 查看服务日志 |
此方案提供了完整的 Docker 化运行环境,并集成了:
- NATS 消息代理(用于服务间通信)
- Prometheus(指标收集)
- Grafana(指标可视化)
- Jaeger(分布式追踪)
所有组件通过 Docker Compose 一键启动,适合开发和生产环境使用。