Docker 安装 Nginx
讲解使用 Docker 查询、拉取并运行官方 Nginx Web 服务器容器的完整流程与端口映射参数,并在本地已缓存的 `nginx:1.27-alpine` 容器中离线实测版本输出、镜像元数据及 `nginx -t` 配置校验。
学完这一章,你能够
- 讲解使用 Docker 查询、拉取并运行官方 Nginx Web 服务器容器的完整流程与端口映射参数,并在本地已缓存的 `nginx:1.27-alpine` 容器中离线实测版本输出、镜像元数据及 `nginx -t` 配置校验。
Nginx 镜像查找与拉取
Nginx 是兼具高性能 HTTP Web 服务、反向代理负载均衡以及 IMAP/POP3/SMTP 邮件代理能力的轻量级服务器。在 Docker 中部署前,既可浏览 Docker Hub 官方 Nginx 标签页(`https://hub.docker.com/_/nginx?tab=tags`)通过排序或下拉框挑选稳定版/Alpine 精简版(不指定版本默认对应 `nginx:latest`),也可在终端运行 `docker search nginx` 检索镜像仓库(关注 `OFFICIAL` 列标记 `[OK]` 的官方镜像及 `STARS` 关注度)。
选定官方镜像后,执行 `docker pull nginx:latest`(或指定具体版本如 `nginx:1.27-alpine`)拉取到本地,随后运行 `docker images` 确认 `nginx` 镜像及其标签、大小已完整显示在本地镜像库中。
运行 Nginx 容器、端口映射与离线实测
镜像就绪后,使用 `docker run --name nginx-test -p 8080:80 -d nginx` 启动容器:其中 `--name nginx-test` 指定容器名称,`-p 8080:80` 将宿主机 `8080` 端口映射到容器内部 Nginx 默认监听的 `80` 端口,`-d` 使容器转入后台持续守护运行(官方镜像默认 `CMD` 为 `nginx -g 'daemon off;'` 保证主进程驻留前台)。容器启动成功后,在宿主机浏览器访问 `http://localhost:8080` 即可看到 Nginx 欢迎页。本站在本地离线只读检查了已缓存的 `nginx:1.27-alpine` 镜像元数据,并在 `--rm --network none` 临时容器内实测 `nginx -v`(输出 `nginx/1.27.5`)与 `nginx -t` 均校验通过。
离线检查本地缓存 nginx:1.27-alpine 元数据并实测 nginx -v 与 nginx -t
"""Offline Docker Nginx installation verification using cached nginx:1.27-alpine."""
import json
import shlex
import shutil
import subprocess
import sys
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: search / pull / images check against locally cached nginx:1.27-alpine
imgs = run_docker("images", "--format", "{{.Repository}}:{{.Tag}}")
assert imgs.returncode == 0, imgs.stderr
cached_nginx = [ln.strip() for ln in imgs.stdout.splitlines() if ln.strip().startswith("nginx:")]
search_columns = ["NAME", "DESCRIPTION", "STARS", "OFFICIAL", "AUTOMATED"]
pull_tokens = shlex.split("docker pull nginx:latest")
actual_1 = {
"search_columns": search_columns,
"pull_target": pull_tokens[-1],
"cached_nginx_present": "nginx:1.27-alpine" in cached_nginx,
}
expected_1 = {
"search_columns": ["NAME", "DESCRIPTION", "STARS", "OFFICIAL", "AUTOMATED"],
"pull_target": "nginx:latest",
"cached_nginx_present": True,
}
cases.append({
"name": "nginx_search_pull_and_images_spec",
"summary": "验证 docker search nginx 输出列、docker pull nginx:latest 命令及本地已缓存 nginx:1.27-alpine 镜像。",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: docker run --name nginx-test -p 8080:80 -d nginx parsing
run_tokens = shlex.split("docker run --name nginx-test -p 8080:80 -d nginx")
host_port, container_port = run_tokens[run_tokens.index("-p") + 1].split(":", 1)
actual_2 = {
"container_name": run_tokens[run_tokens.index("--name") + 1],
"host_port": int(host_port),
"container_port": int(container_port),
"detached": "-d" in run_tokens,
"image": run_tokens[-1],
}
expected_2 = {
"container_name": "nginx-test",
"host_port": 8080,
"container_port": 80,
"detached": True,
"image": "nginx",
}
cases.append({
"name": "nginx_run_port_mapping_spec",
"summary": "解析 docker run --name nginx-test -p 8080:80 -d nginx 的端口映射(宿主机 8080 -> 容器 80)与后台运行参数。",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: Read-only docker inspect nginx:1.27-alpine
insp = run_docker("inspect", "nginx:1.27-alpine")
assert insp.returncode == 0, insp.stderr
cfg = json.loads(insp.stdout)[0]["Config"]
actual_3 = {
"exposed_80_tcp": "80/tcp" in (cfg.get("ExposedPorts") or {}),
"entrypoint": cfg.get("Entrypoint"),
"cmd": cfg.get("Cmd"),
}
expected_3 = {
"exposed_80_tcp": True,
"entrypoint": ["/docker-entrypoint.sh"],
"cmd": ["nginx", "-g", "daemon off;"],
}
cases.append({
"name": "nginx_cached_image_inspect",
"summary": "只读检查本地缓存镜像 nginx:1.27-alpine 的 80/tcp 暴露端口、入口脚本与前台守护默认命令。",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: Real ephemeral offline container run (--rm --network none) testing nginx -v and nginx -t
ver = run_docker("run", "--rm", "--network", "none", "--entrypoint", "nginx", "nginx:1.27-alpine", "-v")
tst = run_docker("run", "--rm", "--network", "none", "--entrypoint", "nginx", "nginx:1.27-alpine", "-t")
assert ver.returncode == 0 and tst.returncode == 0, ver.stderr + tst.stderr
ver_line = (ver.stdout + ver.stderr).strip()
tst_out = (tst.stdout + tst.stderr).strip()
actual_4 = {
"version_prefix_ok": ver_line.startswith("nginx version: nginx/1.27."),
"config_syntax_ok": "syntax is ok" in tst_out,
"config_test_successful": "test is successful" in tst_out,
}
expected_4 = {
"version_prefix_ok": True,
"config_syntax_ok": True,
"config_test_successful": True,
}
cases.append({
"name": "nginx_container_version_and_config_test",
"summary": "以 --rm --network none 离线运行 nginx:1.27-alpine,实测 nginx -v 版本输出与 nginx -t 默认配置校验通过。",
"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()
- 确认 nginx 搜索/拉取/运行参数解析准确,只读 inspect 验证 80/tcp 暴露端口与 daemon off 默认命令,且离线容器内 nginx -v 与 nginx -t 均成功通过。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:a677515010e25c9834aa24fb4a7a088f1382b8e19bee46ee615bf585daf1437a
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:ac3d0ae3b6cd4fd64e31a191df29683315532c3fd28a2fa16a7f4dbc34332f7a
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么在 `docker run --name nginx-test -p 8080:80 -d nginx` 中,Nginx 镜像默认要使用 `nginx -g 'daemon off;'` 而不是传统的后台守护模式启动?
展开参考解答
Docker 容器的生命周期与 1 号进程(PID 1)绑定;若 Nginx 以传统 daemon 模式将自身 fork 到后台并退出父进程,Docker 会判定主进程结束并立即停止整个容器,因此必须强制前台运行。