docker安装prometheus和Grafana
一、准备配置文件(prometheus.yml
)
先在主机上创建一个配置文件目录
mkdir -p ~/prometheus
cd ~/prometheus
然后创建配置文件 prometheus.yml
:
global:scrape_interval: 15sscrape_configs:- job_name: 'prometheus'static_configs:- targets: ['localhost:9090']
如果你要监控其他服务,比如 node_exporter、blackbox_exporter 等,可以在这里添加新的 job。
二、运行 Prometheus 容器
使用以下 Docker 命令运行 Prometheus:
docker run -d \--name prometheus \-p 9090:9090 \-v ~/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml \prom/prometheus
参数解释:
-d
:后台运行
--name prometheus
:容器命名为 prometheus
-p 9090:9090
:将容器端口映射到主机(默认端口)
-v
:挂载本地配置文件到容器中
三、访问 Prometheus
浏览器打开:
http://localhost:9090
如果你是远程服务器,使用公网 IP 访问:
http://<your-server-ip>:9090
四、检查容器状态
docker ps
如果需要查看日志:
docker logs -f prometheus
一、Docker 部署 Grafana
docker run -d \--name=grafana \-p 3000:3000 \-v grafana-storage:/var/lib/grafana \grafana/grafana-oss
参数说明:
-d
:后台运行
--name=grafana
:容器名
-p 3000:3000
:把容器 3000 端口映射到主机
-v grafana-storage:/var/lib/grafana
:持久化存储
grafana/grafana-oss
:官方开源版本镜像
二、访问 Grafana
浏览器打开:
http://localhost:3000
如果是服务器:
http://<你的服务器IP>:3000
默认账号密码:
用户名:
admin
密码:
admin
(首次登录会要求修改)
三、添加 Prometheus 数据源
登录 Grafana 后,左侧点击 “⚙️ Configuration” → “Data sources”
点击 “Add data source”
选择 Prometheus
URL 填写:
http://<prometheus容器IP或主机IP>:9090
或者如果你用 Docker Compose 并定义了网络,可直接用容器名:
http://prometheus:9090
- 点击 “Save & Test”
四、可选:Grafana 配置持久化(挂载本地目录)
如果你想让配置和仪表盘持久保留,可以这样运行:
mkdir -p ~/grafana_datadocker run -d \--name=grafana \-p 3000:3000 \-v ~/grafana_data:/var/lib/grafana \grafana/grafana-oss
五、配合 Prometheus 使用(推荐 Docker Compose)
任意目录下创建一个名为 docker-compose.yml
的文件,内容如下
version: '3.3'services:prometheus:image: prom/prometheuscontainer_name: prometheusports:- "9090:9090"volumes:- ./prometheus/prometheus.yml:/etc/prometheus/prometheus.ymlrestart: unless-stoppedgrafana:image: grafana/grafana-osscontainer_name: grafanaports:- "3000:3000"environment:- GF_SECURITY_ADMIN_USER=admin- GF_SECURITY_ADMIN_PASSWORD=adminvolumes:- grafana-storage:/var/lib/grafanarestart: unless-stoppedvolumes:grafana-storage:
同目录下放置 prometheus.yml
创建目录并写入配置文件:
mkdir -p ./prometheus
nano ./prometheus/prometheus.yml
写入一个最基本的配置,比如:
global:scrape_interval: 15sscrape_configs:- job_name: 'prometheus'static_configs:- targets: ['prometheus:9090']
启动服务
在 docker-compose.yml
所在目录运行:
docker-compose up -d
把 /root/project_py/prometheus
目录下的规则文件都挂载给 Prometheus 使用
在 docker-compose.yml
里增加目录挂载
services:prometheus:image: prom/prometheuscontainer_name: prometheusports:- "9090:9090"volumes:- ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml- /root/project_py/prometheus:/etc/prometheus/rules # 这里挂载你的规则目录restart: unless-stopped
修改你的 prometheus.yml
配置文件,让 Prometheus 读取这个目录下的所有规则文件:
rule_files:- "/etc/prometheus/rules/*.yml"
或者如果你的规则文件后缀是 .rules
,就写成:
rule_files:- "/etc/prometheus/rules/*.rules"
Prometheus 容器内规则目录是
/etc/prometheus/rules
(你自己指定的挂载路径)规则文件必须是 YAML 格式,且符合 Prometheus 规则语法
你可以放多个规则文件,Prometheus 会加载所有匹配的文件
最后:重启 Prometheus
docker-compose up -d