AWS EKS部署Prometheus和Grafana:从零开始的监控搭建指南

作为一名长期与Kubernetes打交道的技术博主,我深知监控系统对于生产环境的重要性。今天,我将手把手教你如何在AWS EKS(Elastic Kubernetes Service)上部署Prometheus和Grafana,实现集群监控的可视化。本文适合有一定Kubernetes基础,但刚接触EKS监控的开发者。## 为什么选择Prometheus+Grafana?在Kubernetes生态中,Prometheus是事实上的监控标准,它能自动发现服务并收集指标;而Grafana则提供了强大的可视化仪表盘。两者结合,可以轻松监控EKS集群的CPU、内存、网络等关键指标。AWS EKS虽然内置了CloudWatch监控,但Prometheus的灵活性和细粒度指标收集能力无可替代。比如,你可以监控Pod级别的自定义业务指标,这在CloudWatch中实现起来较为复杂。## 准备工作:环境与工具在开始之前,请确保你已经准备好:- 一个正在运行的AWS EKS集群(版本1.21+)- kubectl 命令行工具已配置好集群访问权限- helm v3+ 包管理器(推荐使用Helm简化部署)如果你还没有EKS集群,可以通过AWS CLI快速创建:bashaws eks create-cluster --name my-monitoring-cluster --role-arn arn:aws:iam::<account-id>:role/eksClusterRole --resources-vpc-config subnetIds=subnet-xxx,subnet-yyy## 第一步:使用Helm部署PrometheusPrometheus可以通过多种方式部署,但使用Prometheus Operator是最佳实践。它将Prometheus配置抽象为Kubernetes自定义资源,大大简化了管理。首先,添加Helm仓库并安装Prometheus Stack(包含Prometheus、AlertManager和Node Exporter):bash# 添加Prometheus社区仓库helm repo add prometheus-community https://prometheus-community.github.io/helm-chartshelm repo update# 创建命名空间kubectl create namespace monitoring# 安装Prometheus Stackhelm install prometheus prometheus-community/kube-prometheus-stack \ --namespace monitoring \ --set grafana.enabled=false \ --set prometheus.service.type=LoadBalancer这里我暂时禁用了Grafana,因为稍后我们会单独配置它。prometheus.service.type=LoadBalancer 会让Prometheus暴露一个公网负载均衡器,方便外部访问。### 代码示例1:验证Prometheus部署部署完成后,用以下Python脚本检查Prometheus是否正常运行。这个脚本会调用Kubernetes API来验证Pod状态。pythonimport subprocessimport jsonimport sysdef check_prometheus_deployment(): """检查Prometheus相关Pod的状态""" try: # 获取monitoring命名空间下的所有Pod result = subprocess.run( ["kubectl", "get", "pods", "-n", "monitoring", "-o", "json"], capture_output=True, text=True, check=True ) pods = json.loads(result.stdout) print("=== Prometheus 部署状态 ===") for pod in pods['items']: name = pod['metadata']['name'] status = pod['status']['phase'] # 检查是否包含Prometheus关键字 if 'prometheus' in name.lower(): print(f"Pod: {name}") print(f"状态: {status}") # 检查容器是否就绪 for condition in pod['status'].get('conditions', []): if condition['type'] == 'Ready': print(f"就绪状态: {condition['status']}") print("---") # 统计健康的Pod数量 healthy_pods = sum( 1 for pod in pods['items'] if 'prometheus' in pod['metadata']['name'].lower() and pod['status']['phase'] == 'Running' ) print(f"健康运行的Prometheus Pod数量: {healthy_pods}") if healthy_pods == 0: print("警告:没有Prometheus Pod在运行!") sys.exit(1) else: print("Prometheus部署成功!") except subprocess.CalledProcessError as e: print(f"Kubectl命令执行失败: {e}") sys.exit(1) except Exception as e: print(f"发生未知错误: {e}") sys.exit(1)if __name__ == "__main__": check_prometheus_deployment()运行这个脚本,你会看到类似输出:=== Prometheus 部署状态 ===Pod: prometheus-kube-prometheus-stack-prometheus-0状态: Running就绪状态: True---健康运行的Prometheus Pod数量: 1Prometheus部署成功!## 第二步:部署Grafana并与Prometheus集成Grafana负责将Prometheus收集的数据可视化。我们单独部署Grafana,这样可以更灵活地配置数据源。使用Helm安装Grafana,并配置连接到Prometheus:bash# 添加Grafana仓库helm repo add grafana https://grafana.github.io/helm-chartshelm repo update# 安装Grafana,并配置Prometheus数据源helm install grafana grafana/grafana \ --namespace monitoring \ --set datasources."datasources\.yaml".apiVersion=1 \ --set datasources."datasources\.yaml".datasources[0].name=Prometheus \ --set datasources."datasources\.yaml".datasources[0].type=prometheus \ --set datasources."datasources\.yaml".datasources[0].url=http://prometheus-kube-prometheus-stack-prometheus.monitoring.svc:9090 \ --set datasources."datasources\.yaml".datasources[0].access=proxy \ --set datasources."datasources\.yaml".datasources[0].isDefault=true \ --set service.type=LoadBalancer这里的关键是datasources配置,它告诉Grafana如何连接到Prometheus。url指向Prometheus的Kubernetes服务地址,格式为<service-name>.<namespace>.svc:9090。### 代码示例2:配置Grafana仪表盘部署完成后,我们需要获取Grafana的访问密码,然后配置一个默认仪表盘。以下Python脚本会自动完成这些操作:pythonimport subprocessimport jsonimport requestsimport base64def setup_grafana_dashboard(): """自动配置Grafana仪表盘""" try: # 获取Grafana管理员密码 result = subprocess.run( ["kubectl", "get", "secret", "--namespace", "monitoring", "grafana", "-o", "jsonpath={.data.admin-password}"], capture_output=True, text=True, check=True ) # 解码Base64密码 admin_password = base64.b64decode(result.stdout.strip()).decode('utf-8') admin_user = "admin" print(f"Grafana管理员账号: {admin_user}") print(f"密码: {admin_password}") # 获取Grafana服务的外部IP result = subprocess.run( ["kubectl", "get", "svc", "--namespace", "monitoring", "grafana", "-o", "jsonpath={.status.loadBalancer.ingress[0].hostname}"], capture_output=True, text=True, check=True ) grafana_host = result.stdout.strip() grafana_url = f"http://{grafana_host}:3000" print(f"Grafana访问地址: {grafana_url}") # 登录Grafana API session = requests.Session() login_data = { "user": admin_user, "password": admin_password } login_response = session.post(f"{grafana_url}/login", json=login_data) if login_response.status_code != 200: print(f"登录失败: {login_response.text}") return print("成功登录Grafana!") # 导入Kubernetes集群监控仪表盘(ID为315) dashboard_id = 315 import_response = session.post( f"{grafana_url}/api/dashboards/import", json={ "dashboard": {"id": None}, "overwrite": True, "inputs": [{ "name": "DS_PROMETHEUS", "type": "datasource", "pluginId": "prometheus", "value": "Prometheus" }], "dashboardId": dashboard_id } ) if import_response.status_code == 200: print(f"成功导入仪表盘 ID: {dashboard_id}") print("现在你可以通过浏览器访问Grafana查看监控数据!") else: print(f"导入仪表盘失败: {import_response.text}") except subprocess.CalledProcessError as e: print(f"命令执行失败: {e}") except requests.exceptions.RequestException as e: print(f"网络请求失败: {e}") except Exception as e: print(f"发生未知错误: {e}")if __name__ == "__main__": setup_grafana_dashboard()这个脚本会:1. 自动获取Grafana的管理员密码2. 获取负载均衡器的外部地址3. 通过API登录Grafana4. 导入一个预配置的Kubernetes监控仪表盘(ID 315)## 验证监控效果现在,打开浏览器访问Grafana的外部地址(脚本中已经输出),使用admin和获取到的密码登录。你应该能看到一个包含CPU、内存、网络等指标的仪表盘。如果数据没有立刻显示,别担心——Prometheus需要几分钟来收集数据。你可以手动触发一些负载来测试:bash# 创建一个测试Pod,模拟CPU压力kubectl run stress-test --image=busybox -- sh -c "while true; do :; done" --namespace default观察Grafana仪表盘,你会看到CPU使用率上升。## 常见问题与优化1. 存储持久化:默认情况下,Prometheus的数据存储在临时卷中。生产环境建议配置持久卷: bash helm upgrade prometheus prometheus-community/kube-prometheus-stack \ --set prometheus.prometheusSpec.storageSpec.volumeClaimTemplate.spec.accessModes[0]=ReadWriteOnce \ --set prometheus.prometheusSpec.storageSpec.volumeClaimTemplate.spec.resources.requests.storage=50Gi 2. 安全加固:不要在生产环境使用LoadBalancer暴露Prometheus和Grafana。建议使用Ingress配合TLS和认证。3. 资源限制:根据集群规模调整Prometheus的资源请求: bash --set prometheus.prometheusSpec.resources.requests.memory=2Gi \ --set prometheus.prometheusSpec.resources.limits.memory=4Gi ## 总结通过本文,你学会了:- 使用Helm在EKS上快速部署Prometheus和Grafana- 通过Python脚本自动化验证部署状态- 配置Grafana数据源并导入预定义仪表盘- 处理常见部署问题这套监控方案不仅适用于EKS,也适用于其他Kubernetes集群。关键点在于理解Prometheus的服务发现机制和Grafana的数据源配置。希望这篇文章能帮助你快速搭建起生产级的监控系统。如果你有任何问题,欢迎在评论区交流讨论!

更多推荐