Docker 安装 Nginx

用官方镜像跑 Nginx、挂载配置与静态文件、做反向代理。

Beginner
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   # 热加载,不断连接

常见问题

SymptomCauseFix
502 Bad GatewayUpstream host not resolvableJoin the same network
403 ForbiddenSELinux label on the mountAdd :z to the volume
Config change ignoredContainer not reloadednginx -s reload
host not found in upstreamUpstream not started yetdepends_on + healthcheck

Friends & Partners