Docker 安装 Nginx
用官方镜像跑 Nginx、挂载配置与静态文件、做反向代理。
Key Points官方镜像的配置在 /etc/nginx/conf.d/*.conf,静态文件在 /usr/share/nginx/html;改配置要 reload 不是 restart。
最快跑起来
Bash
docker run -d --name nginx -p 8080:80 nginx:1.27-alpine
curl -I http://127.0.0.1:8080挂载静态站点
Bash
docker run -d --name site -p 8080:80 \
-v "$PWD/dist:/usr/share/nginx/html:ro" \
nginx:1.27-alpine自定义配置 + 反向代理
NGINX
server {
listen 80;
server_name _;
location /static/ {
alias /usr/share/nginx/html/;
expires 7d;
}
location /api/ {
proxy_pass http://api:8080/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}Bash
docker run -d --name nginx \
-p 80:80 \
-v "$PWD/nginx.conf:/etc/nginx/conf.d/default.conf:ro" \
--network app-net \
nginx:1.27-alpine
docker exec nginx nginx -t # 先测配置
docker exec nginx nginx -s reload # 热加载,不断连接常见问题
| Symptom | Cause | Fix |
|---|---|---|
| 502 Bad Gateway | Upstream host not resolvable | Join the same network |
| 403 Forbidden | SELinux label on the mount | Add :z to the volume |
| Config change ignored | Container not reloaded | nginx -s reload |
host not found in upstream | Upstream not started yet | depends_on + healthcheck |
最快跑起来
Bash
docker run -d --name nginx -p 8080:80 nginx:1.27-alpine
curl -I http://127.0.0.1:8080挂载静态站点
Bash
docker run -d --name site -p 8080:80 \
-v "$PWD/dist:/usr/share/nginx/html:ro" \
nginx:1.27-alpine自定义配置 + 反向代理
NGINX
server {
listen 80;
server_name _;
location /static/ {
alias /usr/share/nginx/html/;
expires 7d;
}
location /api/ {
proxy_pass http://api:8080/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}Bash
docker run -d --name nginx \
-p 80:80 \
-v "$PWD/nginx.conf:/etc/nginx/conf.d/default.conf:ro" \
--network app-net \
nginx:1.27-alpine
docker exec nginx nginx -t # 先测配置
docker exec nginx nginx -s reload # 热加载,不断连接常见问题
| 现象 | 原因 | 处理 |
|---|---|---|
| 502 | 上游主机名解析不了 | 加入同一网络 |
| 403 | 挂载目录的 SELinux 标签 | 挂载加 :z |
| 改配置不生效 | 没重载 | nginx -s reload |
| 上游解析失败 | 上游还没起 | depends_on + 健康检查 |