Récemment voulu configurerSpring BootApplicationPrometheus+GrafanaSurveillancedemo,Découvrez beaucoup d'informations en anglais et en chinois sur Internet,Contenu obsolète ou mal configuré.
Écrivez donc un article sur le fonctionnement de l'ensemble du système.
DemoL'adresse source de:
-
https://github.com/hengyunabc/spring-boot-prometheus-grafana-demo
spring bootApplicationmetricsConfiguration
Tout d'abord,,Nous allons directement sur le site officiel pour créer unspring boot demoApplication:
-
https://start.spring.io/
Une fois créé,On est là.pom.xml
Ajouter les dépendances suivantes:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
-
spring-boot-starter-actuator Soutienspring bootExpositionhttp endpoint -
micrometer-registry-prometheus Soutienprometheus endpoint, Cette exposition est OpenMetrics
Format de,prometheus Collecte de données à partir d'ici .
Regarde encore. application.properties
Documentation:
spring.application.name=expose-prometheus-demo
server.port=8080
management.endpoints.web.exposure.include=*
management.server.port=8090
management.metrics.tags.application=${spring.application.name}
-
management.server.port
Configurationendpoint Pour les ports autonomes , Mélanger le même port avec l'application peut causer des problèmes de sécurité -
management.metrics.tags.application
Configurationmetric- Oui.application
Detag
Après le démarrage local de l'application ,Accès à http://localhost:8090/actuator/prometheus ,Je vois.metrics Les données ont application
Detag:
# TYPE jvm_classes_unloaded_classes_total counter
jvm_classes_unloaded_classes_total{application="expose-prometheus-demo",} 0.0
Configurationk8sEnvironnement
Démarrageminikube k8sCluster
minikube start --image-mirror-country='cn' --nodes 2 --kubernetes-version=v1.18.3
$ kubectl get nodes
NAME STATUS ROLES AGE VERSION
minikube Ready master 65s v1.18.3
minikube-m02 NotReady <none> 30s v1.18.3
ConstruiredockerMiroir
Emballezspring boot fat jar:
./mvnw clean package -DskipTests
docker build . -t hengyunabc/expose-prometheus-demo:0.0.1-SNAPSHOT
Test de démarrage local :
docker run -it -p8080:8080 -p8090:8090 hengyunabc/expose-prometheus-demo:0.0.1-SNAPSHOT
Accès à:http://localhost:8090/actuator/prometheus
Installationprometheus
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update
helm install prometheus prometheus-community/kube-prometheus-stack
OuvertPrometheus UITransfert de port:
kubectl port-forward $(kubectl get pods --selector "app.kubernetes.io/name=prometheus" --output=name) 9090
Ouvertgrafana UITransfert de port:
kubectl port-forward $(kubectl get pods --selector "app.kubernetes.io/name=grafana" --output=name) 3000
Publicationspring bootAppliquer àk8s
kubectl apply -f ./servicemonitor-deployment.yaml
Inservicemonitor-deployment.yaml
Il y en a trois. .Notez queService
EtServiceMonitor
Il faut tout mettre label: release: prometheus
.
Deployment
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: expose-prometheus-demo
labels:
app: expose-prometheus-demo
spec:
replicas: 1
selector:
matchLabels:
app: expose-prometheus-demo
template:
metadata:
labels:
app: expose-prometheus-demo
spec:
containers:
- name: expose-prometheus-demo
image: hengyunabc/expose-prometheus-demo:0.0.1-SNAPSHOT
imagePullPolicy: Always
ports:
- containerPort: 8080
- containerPort: 8090
Service
---
apiVersion: v1
kind: Service
metadata:
name: expose-prometheus-demo-service
labels:
app: expose-prometheus-demo
release: prometheus
spec:
selector:
app: expose-prometheus-demo
ports:
- protocol: TCP
name: http-traffic
port: 8080
targetPort: 8080
- protocol: TCP
name: metric-traffic
port: 8090
targetPort: 8090
ServiceMonitor
---
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: expose-prometheus-demo-service-monitor
labels:
app: expose-prometheus-demo
release: prometheus
spec:
selector:
matchLabels:
app: expose-prometheus-demo
endpoints:
- port: metric-traffic
path: "/actuator/prometheus"
Application publiée à k8s Après. ,Accès àPrometheus UI, Vous pouvez voir si vous avez trouvé demoDeService Discovery
-
http://localhost:9090/service-discovery
Comment ça marche
Voici une analyse en deux parties du fonctionnement de l'ensemble du processus. .
Première partie:
-
spring boot Application par l'introduction de prometheus
endpoint, Les données sont exposées à http://localhost:8090/actuator/prometheus -
prometheusDéjàk8s Il est déployé , C'est une machine à saisir impitoyable , Il faut trouver un moyen de le tirer. spring bootDonnées appliquées -
prometheus Configuration réelle en cours d'exécution ,Accessible http://localhost:9090/config Voir. Ici aussi, la vérification ServiceMonitor
Un endroit où cela fonctionne ou non .
Deuxième partie:
-
Déploiementkind Service
,labelAvecrelease: prometheus
-
Déploiementkind ServiceMonitor
,labelAvecrelease: prometheus
-
Prometheus operator Vous trouverez de nouveaux déploiements ServiceMonitor
,Et générer un nouveauprometheusConfiguration,Enregistrer àk8sDeSecrets- Oui., L'enregistrement réel du fichier est compressé :prometheus.yaml.gz
-
prometheus-config-reloaderJe vais mettre ça. prometheus.yaml.gz
Décompresser à/etc/prometheus/config_out/prometheus.env.yaml
-
prometheus
Démarrer avec--config.file
Paramètre spécifié ci - dessusprometheus.env.yaml
Voir les photos officielles :
Configurationgrafana
-
http://localhost:3000/
grafana Le mot de passe par défaut du nom d'utilisateur est :
admin/prom-operator
Importer d'abord les sources ouvertes suivantes JVM (Micrometer)
dashboard:
-
https://grafana.com/grafana/dashboards/4701
InGrafana UI- Oui.,InDashboards
,Manage
,Import
,Remplissage4701
.Après l'importation réussie,Juste là.DashboardsJe l'ai trouvé.JVM (Micrometer)
.
On peut voir expose-prometheus-demoInformations de surveillance pour.
Méthode de dépannage
C'est le but maintenant , Pourquoi les configurations basées sur des données en ligne ne fonctionnent - elles pas? ?Parce quePrometheus Operator Elle est constamment mise à jour. , Donc certaines configurations sont obsolètes .
-
Voir avec compétence k8s Toutes sortes de ressources
Comme regarderk8s- Oui.PrometheusQuestions connexespodInformation:
kubectl get pod prometheus-prometheus-kube-prometheus-prometheus-0 -o yaml
Nous pouvons le savoir à partir des résultats prometheus-config-reloader
Quelle est la configuration de :
- args:
- --listen-address=:8080
- --reload-url=http://127.0.0.1:9090/-/reload
- --config-file=/etc/prometheus/config/prometheus.yaml.gz
- --config-envsubst-file=/etc/prometheus/config_out/prometheus.env.yaml
- --watched-dir=/etc/prometheus/rules/prometheus-prometheus-kube-prometheus-prometheus-rulefiles-0
command:
- /bin/prometheus-config-reloader
-
Compris. ServiceMonitor
Comment fonctionne - t - il?
InComment ça marche
Dans une section , Le schéma officiel est le suivant: kind
PourPrometheus
Ressources. Donc nous avons installé prometheus operatorAprès,Vous pouvez voir les détailsyamlConfiguration.
$ kubectl get Prometheus
NAME VERSION REPLICAS AGE
prometheus-kube-prometheus-prometheus v2.28.1 1 2d23h
$ kubectl get Prometheus prometheus-kube-prometheus-prometheus -o yaml
Dans les résultats yaml- Oui.,On peut le trouver.serviceMonitorSelector
Informations de configuration pour:
serviceMonitorSelector:
matchLabels:
release: prometheus
C'est pourquoi nous devonsDemoÀ l'intérieur.servicemonitor-deployment.yaml
En configuration intérieure release: prometheus
, C'est pourquoi beaucoup de tutoriels ne fonctionnent pas. .
-
Le processus de configuration est déclenché asynchrone
De l'applicationdeploy,ÀoperatorChangements,Àprometheus reload, Ensuite, saisissez réellement la configuration ,Tout le processus est asynchrone. Les changements peuvent prendre une minute ou deux avant qu'ils ne prennent effet. .
Résumé
-
k8s Le système de surveillance est très puissant. ,Mais c'est aussi plus compliqué, Une couche sur le composant d'origine Operator, Pour réaliser la découverte automatique ,Mise à jour automatique. -
Pour les utilisateurs,Operator C'est du miel et de l'arsenic. , Bien que l'utilisation soit simplifiée , Mais comprendre plus de concepts .
版权声明
本文为[Colonne de Hengyun duanling]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/11/20211125172432420a.html