Nginx 容器部署
Nginx 是最流行的 Web 服务器和反向代理,下面介绍容器化部署方法。
快速部署
Bash
# 最简单部署
docker run -d --name my-nginx -p 80:80 nginx
# 访问测试
curl http://localhost
配置挂载
静态文件挂载
Bash
# 挂载静态网页
docker run -d \
--name my-nginx \
-p 80:80 \
-v /host/html:/usr/share/nginx/html:ro \
nginx
# 宿主机 /host/html/index.html
# <h1>Hello from Docker Nginx</h1>
配置文件挂载
Bash
# 挂载自定义配置
docker run -d \
--name my-nginx \
-p 80:80 \
-v /host/nginx.conf:/etc/nginx/nginx.conf:ro \
-v /host/conf.d:/etc/nginx/conf.d:ro \
nginx
日志挂载
Bash
# 持久化日志
docker run -d \
--name my-nginx \
-p 80:80 \
-v /host/logs:/var/log/nginx \
nginx
反向代理配置
创建 /host/conf.d/default.conf:
nginx
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
Bash
# 启动 Nginx 反向代理
docker run -d \
--name nginx-proxy \
-p 80:80 \
-v /host/conf.d:/etc/nginx/conf.d:ro \
nginx
完整示例
Bash
# 完整部署 Nginx
docker run -d \
--name web-server \
-p 80:80 \
-p 443:443 \
-v /data/html:/usr/share/nginx/html:ro \
-v /data/conf.d:/etc/nginx/conf.d:ro \
-v /data/logs:/var/log/nginx \
--restart unless-stopped \
nginx:latest
常用操作
Bash
# 重新加载配置(不中断服务)
docker exec my-nginx nginx -s reload
# 测试配置语法
docker exec my-nginx nginx -t
# 查看访问日志
tail -f /host/logs/access.log
# 查看错误日志
tail -f /host/logs/error.log
官方镜像标签
| 标签 | 说明 |
|---|---|
nginx:latest | 最新稳定版 |
nginx:alpine | 基于 Alpine 的精简版 |
nginx:1.25 | 指定版本 |
要点总结
docker run -d -p 80:80 nginx快速部署- 静态文件挂载到
/usr/share/nginx/html,建议只读 - 配置文件挂载到
/etc/nginx/conf.d/,支持自定义 - 日志挂载到
/var/log/nginx便于持久化和分析 nginx -s reload热加载配置,不中断服务
📝 发现内容有误?点击此处直接编辑