温馨提示×

Linux环境下如何监控Node.js应用

小樊
33
2025-12-02 15:21:53
栏目: 编程语言

在Linux环境下监控Node.js应用可以通过多种方法来实现,以下是一些常用的工具和方法:

1. 使用pm2

pm2是一个非常流行的Node.js进程管理器,它提供了丰富的功能来监控和管理Node.js应用。

安装pm2

npm install pm2 -g

启动应用

pm2 start app.js --name "my-app"

监控应用

pm2 monit

查看日志

pm2 logs

2. 使用nodemon

nodemon是一个用于开发环境的工具,它可以监视文件变化并自动重启Node.js应用。

安装nodemon

npm install nodemon -g

启动应用

nodemon app.js

3. 使用htop

htop是一个交互式的进程查看器,可以用来监控系统的CPU、内存等资源使用情况。

安装htop

sudo apt-get install htop

使用htop

htop

4. 使用top

top是一个基本的系统监视工具,可以查看实时运行的进程及其资源使用情况。

使用top

top

5. 使用glances

glances是一个跨平台的系统监视工具,可以监控CPU、内存、磁盘、网络等资源。

安装glances

sudo apt-get install glances

使用glances

glances

6. 使用node-clinic

node-clinic是一个Node.js性能分析工具,可以帮助你诊断性能问题。

安装node-clinic

npm install -g clinic

使用node-clinic

clinic doctor -- node app.js

7. 使用PrometheusGrafana

Prometheus是一个开源的监控系统和时间序列数据库,Grafana是一个开源的分析和监控平台。你可以使用它们来监控Node.js应用。

安装PrometheusGrafana

# 安装Prometheus
wget https://github.com/prometheus/prometheus/releases/download/v2.30.3/prometheus-2.30.3.linux-amd64.tar.gz
tar xvfz prometheus-2.30.3.linux-amd64.tar.gz
cd prometheus-2.30.3.linux-amd64
./prometheus --config.file=prometheus.yml &

# 安装Grafana
sudo apt-get install -y apt-transport-https
sudo apt-get install -y software-properties-common wget
wget -q -O - https://packages.grafana.com/gpg.key | sudo apt-key add -
sudo add-apt-repository "deb https://packages.grafana.com/oss/deb stable main"
sudo apt-get update
sudo apt-get install grafana
sudo systemctl daemon-reload
sudo systemctl start grafana-server
sudo systemctl enable grafana-server

配置Prometheus

编辑prometheus.yml文件,添加Node.js应用的监控配置。

scrape_configs:
  - job_name: 'node'
    static_configs:
      - targets: ['localhost:9100']

启动node_exporter

wget https://github.com/prometheus/node_exporter/releases/download/v1.2.2/node_exporter-1.2.2.linux-amd64.tar.gz
tar xvfz node_exporter-1.2.2.linux-amd64.tar.gz
cd node_exporter-1.2.2.linux-amd64
./node_exporter

Grafana中添加Prometheus数据源

  1. 打开Grafana,进入Configuration -> Data Sources
  2. 点击Add data source,选择Prometheus
  3. URL字段中输入http://localhost:9090,然后点击Save & Test

通过这些工具和方法,你可以有效地监控Node.js应用在Linux环境下的运行状态和性能。

0