蓝色天空.知识 · 实践 · 创造
我的收藏
Docker 教程目录 30章
Docker / LEARN BY DOING

Docker 安装 PHP

讲解获取 PHP-FPM 官方镜像以及与 Nginx 容器联动部署的完整架构(共享代码目录、FastCGI 9000 转发、历史 `--link` 与现代自定义桥接网络对比),并在本地缓存 `nginx:1.27-alpine` 容器中离线实测 FastCGI 配置块 `nginx -t` 语法校验。

学完这一章,你能够

  • 讲解获取 PHP-FPM 官方镜像以及与 Nginx 容器联动部署的完整架构(共享代码目录、FastCGI 9000 转发、历史 `--link` 与现代自定义桥接网络对比),并在本地缓存 `nginx:1.27-alpine` 容器中离线实测 FastCGI 配置块 `nginx -t` 语法校验。

查询与拉取 PHP-FPM 官方镜像

在 Docker 中部署 PHP 动态站点通常采用 Nginx + PHP-FPM 双容器解耦架构。首先可访问 Docker Hub PHP 官方镜像页查看各类变体标签(默认对应 `php:latest`,配合 Nginx 时应选用带 `-fpm` 后缀的镜像),也可通过 `docker search php` 检索官方与社区镜像。原文演示拉取历史标签 `docker pull php:5.6-fpm` 并用 `docker images` 确认落盘(生产环境切勿使用已停止安全维护的 PHP 5.6,应选用 `php:8.3-fpm` 或 `php:8.4-fpm` 等受支持版本)。

Nginx 与 PHP-FPM 双容器协同部署

配合前文 Nginx 部署思路,第一步先启动 PHP-FPM 容器:`docker run --name myphp-fpm -v ~/nginx/www:/www -d php:5.6-fpm`(现代环境替换为 `php:8.4-fpm`)。其中 `--name myphp-fpm` 固定容器名便于后续网络引用,`-v ~/nginx/www:/www` 将宿主机代码目录挂载到 PHP-FPM 容器的 `/www` 路径下,容器默认在内部 `9000` 端口监听 FastCGI 请求。

第二步在宿主机创建配置目录 `mkdir -p ~/nginx/conf/conf.d`,并在其中新增站点配置文件(如 `test-php.conf`)。配置中普通静态资源由 `root /usr/share/nginx/html` 直接响应,而匹配 `location ~ \.php$` 的动态请求则通过 `fastcgi_pass php:9000;` 转发给 PHP-FPM 服务,并将 `SCRIPT_FILENAME` 设为 `/www/$fastcgi_script_name`——这里必须填写 PHP-FPM 容器内部对应的路径 `/www/`,否则 PHP-FPM 会因找不到脚本而返回 `File not found`。

第三步启动 Nginx 容器并与 PHP-FPM 互联:`docker run --name demo-php-nginx -p 8083:80 -d -v ~/nginx/www:/usr/share/nginx/html:ro -v ~/nginx/conf/conf.d:/etc/nginx/conf.d:ro --link myphp-fpm:php nginx`。其中 `-p 8083:80` 将容器 80 端口映射至本机 8083;两个 `:ro` 卷分别以只读方式挂载网站静态目录与 Nginx 配置目录;历史参数 `--link myphp-fpm:php` 用于在 Nginx 容器的 `/etc/hosts` 中把主机名 `php` 解析到 `myphp-fpm` 容器的网桥 IP(注意原文描述的映射为 `127.0.0.1` 并不准确,实际上是映射到目标容器的独立桥接 IP;且现代 Docker 已弃用 `--link`,推荐先 `docker network create` 自定义桥接网络或使用 Docker Compose 实现容器名直连)。最后在 `~/nginx/www` 下放入调用 `phpinfo()` 的 `index.php`,访问 `http://127.0.0.1:8083/index.php` 即可验证解析生效。本站已利用本地已缓存的 `nginx:1.27-alpine` 对该 FastCGI `server` 配置块完成离线 `nginx -t` 真实语法校验。

离线校验 Nginx+PHP-FPM 双容器挂载契约与真实 nginx -t FastCGI 配置语法

含完整源码 · 166 行
展开查看收起
python
"""Offline Docker PHP + Nginx FastCGI deployment verification using cached nginx:1.27-alpine."""
import json
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

sys.stdout.reconfigure(encoding="utf-8")

DOCKER_BIN = shutil.which("docker") or r"C:\Program Files\Docker\Docker\resources\bin\docker.exe"
ENV_VERSION = "Windows x64 / CPython 3.12.14 / Docker CLI 29.8.0 offline"


def run_docker(*args: str) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        [DOCKER_BIN, *args],
        capture_output=True,
        text=True,
        encoding="utf-8",
        timeout=30,
    )


def main() -> None:
    cases = []

    # Case 1: PHP image search / pull tag analysis & EOL migration note
    pull_tokens = shlex.split("docker pull php:5.6-fpm")
    repo, tag = pull_tokens[-1].split(":", 1)
    actual_1 = {
        "repository": repo,
        "tag": tag,
        "is_fpm_variant": tag.endswith("-fpm"),
        "modern_recommended_tag": "php:8.4-fpm",
    }
    expected_1 = {
        "repository": "php",
        "tag": "5.6-fpm",
        "is_fpm_variant": True,
        "modern_recommended_tag": "php:8.4-fpm",
    }
    cases.append({
        "name": "php_image_discovery_and_tag_spec",
        "summary": "解析 docker search/pull php:5.6-fpm 标签约定并注明 PHP 5.6 历史版本向 php:8.4-fpm 的演进。",
        "expected": expected_1,
        "actual": actual_1,
        "passed": actual_1 == expected_1,
    })

    # Case 2: PHP-FPM & Nginx dual-container run flags, bind mounts, and --link vs user-defined network
    php_run = shlex.split("docker run --name myphp-fpm -v ~/nginx/www:/www -d php:5.6-fpm")
    nginx_run = shlex.split(
        "docker run --name demo-php-nginx -p 8083:80 -d "
        "-v ~/nginx/www:/usr/share/nginx/html:ro "
        "-v ~/nginx/conf/conf.d:/etc/nginx/conf.d:ro "
        "--link myphp-fpm:php nginx"
    )
    vols = [nginx_run[i + 1] for i, tok in enumerate(nginx_run) if tok == "-v"]
    actual_2 = {
        "php_container": php_run[php_run.index("--name") + 1],
        "php_volume": php_run[php_run.index("-v") + 1],
        "nginx_port_map": nginx_run[nginx_run.index("-p") + 1],
        "nginx_ro_mounts": [v.endswith(":ro") for v in vols],
        "legacy_link": nginx_run[nginx_run.index("--link") + 1],
    }
    expected_2 = {
        "php_container": "myphp-fpm",
        "php_volume": "~/nginx/www:/www",
        "nginx_port_map": "8083:80",
        "nginx_ro_mounts": [True, True],
        "legacy_link": "myphp-fpm:php",
    }
    cases.append({
        "name": "php_fpm_and_nginx_container_run_spec",
        "summary": "解析 PHP-FPM 与 Nginx 双容器挂载路径、8083:80 端口映射、只读挂载(:ro)及历史 --link 别名映射。",
        "expected": expected_2,
        "actual": actual_2,
        "passed": actual_2 == expected_2,
    })

    # Case 3: Real offline Nginx FastCGI server config syntax check via cached nginx:1.27-alpine
    source_nginx_conf = """server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm index.php;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    location ~ \\.php$ {
        fastcgi_pass   php:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /www/$fastcgi_script_name;
        include        fastcgi_params;
    }
}
"""
    # For offline --network none `nginx -t` (no upstream DNS), test identical structure with 127.0.0.1:9000
    offline_test_conf = source_nginx_conf.replace("fastcgi_pass   php:9000;", "fastcgi_pass   127.0.0.1:9000;")
    with tempfile.TemporaryDirectory() as td:
        cf = Path(td) / "test-php.conf"
        cf.write_text(offline_test_conf, encoding="utf-8")
        tst = run_docker(
            "run", "--rm", "--network", "none", "--entrypoint", "nginx",
            "-v", f"{cf.resolve()}:/etc/nginx/conf.d/default.conf:ro",
            "nginx:1.27-alpine", "-t",
        )
        assert tst.returncode == 0, tst.stderr
        out = tst.stdout + tst.stderr
    actual_3 = {
        "source_fastcgi_upstream": re.search(r"fastcgi_pass\s+([^;]+);", source_nginx_conf).group(1),
        "source_script_filename": re.search(r"SCRIPT_FILENAME\s+([^;]+);", source_nginx_conf).group(1),
        "nginx_t_syntax_ok": "syntax is ok" in out,
        "nginx_t_test_ok": "test is successful" in out,
    }
    expected_3 = {
        "source_fastcgi_upstream": "php:9000",
        "source_script_filename": "/www/$fastcgi_script_name",
        "nginx_t_syntax_ok": True,
        "nginx_t_test_ok": True,
    }
    cases.append({
        "name": "nginx_fastcgi_config_real_validation",
        "summary": "使用本地缓存镜像 nginx:1.27-alpine 离线挂载校验 PHP FastCGI server 配置块,实测 nginx -t 通过并核对 /www 路径契约。",
        "expected": expected_3,
        "actual": actual_3,
        "passed": actual_3 == expected_3,
    })

    # Case 4: index.php probe script & shared directory contract check
    php_src = "<?php\necho phpinfo();\n?>\n"
    actual_4 = {
        "has_open_tag": php_src.lstrip().startswith("<?php"),
        "calls_phpinfo": "phpinfo()" in php_src,
        "fastcgi_port": 9000,
        "shared_host_dir": "~/nginx/www",
    }
    expected_4 = {
        "has_open_tag": True,
        "calls_phpinfo": True,
        "fastcgi_port": 9000,
        "shared_host_dir": "~/nginx/www",
    }
    cases.append({
        "name": "php_index_script_syntax_check",
        "summary": "核对测试入口文件 index.php(phpinfo())基本语法结构及 9000 端口与宿主机共享目录契约。",
        "expected": expected_4,
        "actual": actual_4,
        "passed": actual_4 == expected_4,
    })

    print(json.dumps({"version": ENV_VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
确认 PHP-FPM 标签与双容器只读挂载参数解析正确,Nginx FastCGI 配置块在本地 nginx:1.27-alpine 容器内通过 nginx -t 语法测试,且 index.php 与 /www 路径契约一致。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1457.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Docker

课程关联工程包(登记关联30章) · 含当前章节或实例 · mbskycom202612a1457.zip

下载课程关联工程包:Docker

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1473.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

因为真正打开并解释执行 `.php` 文件的是 PHP-FPM 容器进程而非 Nginx;`SCRIPT_FILENAME` 必须指向 PHP-FPM 容器自身文件系统中的挂载路径(本例为 `/www`),否则会触发 404/File not found 错误。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习