要在 PHP 应用中部署 Prometheus,您需要遵循以下步骤:
安装 Prometheus首先,您需要在服务器上安装 Prometheus。请访问 Prometheus 官方网站 并根据您的操作系统下载相应的安装包。然后按照提供的说明进行安装。
安装 PHP 的 Prometheus 客户端库为了从 PHP 应用收集指标,您需要使用一个 Prometheus 客户端库。一个流行的选择是 promphp/prometheus_client_php。要安装这个库,您可以使用 Composer:
composer require promphp/prometheus_client_php配置 PHP 应用以暴露指标在您的 PHP 应用中,您需要设置一个路由(例如 /metrics),该路由将返回 Prometheus 格式的指标数据。以下是一个简单的示例:
<?phprequire 'vendor/autoload.php';use Prometheus\CollectorRegistry;use Prometheus\RenderTextFormat;use Prometheus\Storage\InMemory;use Prometheus\Storage\Redis;$adapter = new InMemory(); // 或者使用 Redis 适配器,如果您希望在多个实例之间共享指标$registry = new CollectorRegistry($adapter);// 创建一个计数器以跟踪请求次数$counter = $registry->registerCounter('my_app', 'requests_total', 'Total number of requests');$counter->inc();// 返回 Prometheus 格式的指标数据header('Content-Type: text/plain; version=0.0.4');echo (new RenderTextFormat())->render($registry->getMetricFamilySamples());配置 Prometheus接下来,您需要配置 Prometheus 以从您的 PHP 应用收集指标。编辑 Prometheus 的配置文件(通常位于 /etc/prometheus/prometheus.yml),并添加一个新的 scrape_config 条目,指向您的 PHP 应用的 /metrics 路由:
scrape_configs: - job_name: 'my_php_app' static_configs: - targets: ['your-php-app.com:9090'] # 替换为您的 PHP 应用的实际地址和端口启动 Prometheus确保 Prometheus 正在运行,并加载了新的配置。您可以使用以下命令启动 Prometheus:
prometheus --config.file=/etc/prometheus/prometheus.yml查看指标现在,您可以在 Prometheus 的 Web 界面中查看您的 PHP 应用的指标。默认情况下,Prometheus 会在 http://localhost:9090 上运行。转到 “Graph” 页面,然后在 “expression” 输入框中输入您的指标名称(例如 my_app_requests_total),以查看和监控您的 PHP 应用的性能指标。
为了更好地可视化和分析您的指标,您可以将 Prometheus 与 Grafana 集成。Grafana 是一个流行的开源仪表板和图形显示平台,可以轻松地展示 Prometheus 收集的数据。请访问 Grafana 官方网站 下载并安装 Grafana,然后按照 官方文档 配置 Prometheus 作为数据源。


