如何在单个容器中启动 PHP-FPM 后启动 Nginx(或监听 http 端口)?

如何在单个容器中启动 PHP-FPM 后启动 Nginx(或监听 http 端口)?

我在 Cloud Run 上的单个容器中运行 Nginx+PHP-FPM 时遇到问题。我的容器基于 Alpine,由 Supervisor 管理 Nginx 和 PHP-FPM 的启动。总体而言,它运行良好,但 Nginx 开始监听 HTTP 端口和 PHP-FPM 启动之间的时间间隔很短。这导致出现 502 HTTP 错误,并显示以下日志消息:

6#6: *3 connect() failed (111: Connection refused) while connecting to upstream, client: 169.254.8.129, server: _, request: "POST / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000"

这里的问题是,Cloud Run 在打开 8080 端口时决定容器已准备好处理请求。端口打开后,Cloud Run 立即发送请求,该请求在第一次尝试时总是会失败,因为 FPM 尚未准备好。NOTICE: fpm is running, pid 4第一个请求到达并失败后,会出现日志消息。

如何管理 Nginx 仅在 PHP-FPM 准备就绪时开放其端口?

主管配置:

[supervisord]
nodaemon=true
logfile=/dev/null
logfile_maxbytes=0
pidfile=/run/supervisord.pid

[program:php-fpm]
command=php-fpm -F
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
autorestart=false
startretries=0

[program:nginx]
command=nginx -g 'daemon off;'
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
autorestart=false
startretries=0

Nginx 配置:

# Write temporary files to /tmp so they can be created as a non-privileged user
client_body_temp_path /tmp/client_temp;
proxy_temp_path /tmp/proxy_temp_path;
fastcgi_temp_path /tmp/fastcgi_temp;
uwsgi_temp_path /tmp/uwsgi_temp;
scgi_temp_path /tmp/scgi_temp;

access_log /dev/stdout;
error_log /dev/stderr notice;

server {
        listen 8080 default_server;

        index index.php;

        keepalive_requests    10;
        keepalive_timeout     60 60;

        root /var/www/html/app/public;

        charset utf-8;

        server_name _;

        # Deny hidden files (.htaccess, .htpasswd, .DS_Store).
        location ~ /\. {
            deny            all;
            access_log      off;
            log_not_found   off;
        }
        ########################
        # mappings             #
        ########################

        location ~ \.(js|css|png|jpg|ico) {
            expires 5d;
            try_files $uri $uri/ =404;
            return 404;
        }

        # Allow fpm ping and status from localhost
        location ~ ^/(fpm-status|fpm-ping)$ {
            access_log off;
            allow 127.0.0.1;
            deny all;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
            fastcgi_pass 127.0.0.1:9000;
        }

        location / {
            client_max_body_size 100m;
            try_files $uri @fpm;
        }

        location @fpm {
            # worker may take long time to finish (max 1 hour)
            fastcgi_read_timeout 3600s;
            fastcgi_split_path_info ^(.+\.php)(/.*)$;
            include fastcgi_params;
            fastcgi_param HTTP_PROXY "";
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /var/www/html/app/public/index.php;
            fastcgi_param SCRIPT_NAME index.php;
        }
}

我已经启用了 FPM ping/状态页面。我可以使用它们来触发 Nginx 端口打开吗?

更新 1:

我尝试调整主管优先级并开始几秒钟:

...
[program:php-fpm]
...
priority=100
startsecs=3

[program:nginx]
...
priority=200

但没有成功:

[18-Dec-2020 00:31:04] NOTICE: ready to handle connections
[18-Dec-2020 00:31:04] NOTICE: fpm is running, pid 3
2020-12-18 00:30:30,689 INFO success: php-fpm entered RUNNING state, process has stayed up for > than 3 seconds (startsecs)
2020-12-18 00:30:28,388 INFO success: nginx entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)
Error POST 502 549 B 3.286 s Google-Cloud-Scheduler https://***.run.app/
169.254.8.129 - - [18/Dec/2020:00:30:27 +0000] "POST / HTTP/1.1" 502 150 "-" "Google-Cloud-Scheduler"
169.254.8.129 - - [18/Dec/2020:00:30:27 +0000] "POST / HTTP/1.1" 502 150 "-" "Google-Cloud-Scheduler" "35.187.131.214"
2020/12/18 00:30:27 [error] 6#6: *3 connect() failed (111: Connection refused) while connecting to upstream, client: 169.254.8.129, server: _, request: "POST / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "***.run.app"
2020-12-18 00:30:26,937 INFO spawned: 'nginx' with pid 4
2020-12-18 00:30:26,829 INFO spawned: 'php-fpm' with pid 3
2020-12-18 00:30:25,730 INFO supervisord started with pid 1
2020-12-18 00:30:25,704 CRIT Supervisor is running as root. Privileges were not dropped because no user

两个应用仍由 Supervisord 同时启动,并且 nginx 首先初始化。SupervisordRUNNING应用于应用的状态对 Cloud Run 毫无意义。

答案1

现在,我得到了以下入口点脚本,该脚本可确保在启动 nginx 之前 PHP-FPM 正在运行:

#!/usr/bin/env sh
set -e

# Start PHP-FPM as a daemon in the background
php-fpm -D

# Wait until PHP-FPM is up and accepts connections. Fail if not started in 10 secs.
for run in $(seq 20)
do
  if [ "$run" -gt "1" ]; then
    echo "Retrying..."
  fi
  RESPONSE=$(
    SCRIPT_NAME=/fpm-ping \
    SCRIPT_FILENAME=/fpm-ping \
    REQUEST_METHOD=GET \
    cgi-fcgi -bind -connect 127.0.0.1:9000 || true)
  case $RESPONSE in
    *"pong"*)
      echo "FPM is running and ready. Starting nginx."
      # Run nginx without exiting to keep the container running
      nginx -g 'daemon off;'
      exit 0
      ;;
  esac
  sleep .5
done
echo "FPM has failed to start on-time, exiting"
exit 1

apk add fcgi命令是需要的(对于 Alpine Linux 而言)。

我还假设该php-fpm -D命令总是在 FPM 准备就绪后退出,因此不需要循环,只需一个接一个地运行命令即可。但我还没有测试过。

答案2

Supervisor 确实可以使用一个startdelay选项,但目前没有。要延迟 nginx 的启动,请将指定的命令更改为 Supervisor(相关主题):

  1. 运行shell睡眠然后直接启动nginx:

    [program:nginx]
    command=bash -c "sleep 5 && exec nginx -g 'daemon off;'"
    ...
    
  2. 运行一个在启动 nginx 之前休眠的脚本:

    [program:nginx]
    command=delayed-nginx.sh
    ...
    

    delayed-nginx.sh

    #!/bin/bash
    sleep 5
    exec nginx -g 'daemon off;'
    

原始答案

我没有专门使用过 Supervisor,但是这个答案php-fpm可能对你有用。这将导致 Supervisor 仅在运行一次时启动 nginx 。

[program:php-fpm]
command=php-fpm -F
...
priority=100

[program:nginx]
command=nginx -g 'daemon off;'
...
priority=200

您可能还需要设置startsecs为更高的值(比默认的 1 秒),以便 Supervisor 仅php-fpm在运行更长时间后才考虑启动,例如 5 秒:

[program:php-fpm]
command=php-fpm -F
...
priority=100
startsecs=5

更多内容请参阅 Supervisor 文档。

相关内容