Nginx 的 compose.yaml
开发环境
shell
# 创建挂载卷目录
mkdir -p /opt/nginx/{conf.d,logs,html,ssl}
# 授权文件夹,防止 nginx 操作文件夹权限不足
chmod -R a+rwx /opt/nginx把 nginx 配置文件,html 静态资源,ssl 证书文件放到对应的位置。
yaml
services:
nginx:
image: nginx:1.31.1
container_name: nginx
restart: unless-stopped
# host 模式直接使用主机网络。无需映射端口。
network_mode: host
# 注意:host模式下,ports 部分必须移除或注释掉。这样配置后,Nginx 会直接监听宿主机的 80 和 443 等端口
#ports:
#- "80:80"
#- "443:443"
volumes:
- /opt/nginx/conf.d:/etc/nginx/conf.d:ro
- /opt/nginx/html:/usr/share/nginx/html:ro
- /opt/nginx/logs:/var/log/nginx
- /opt/nginx/ssl:/etc/nginx/ssl
- /etc/localtime:/etc/localtime:ro
healthcheck:
test: ["CMD-SHELL", "curl -f http://localhost/ || exit 1"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10s挂载卷常用选项:
:ro: 表示只读(read-only)挂载,容器内无法修改该卷的内容。:rw: 默认挂载方式,可读写。/etc/localtime:/etc/localtime:ro:保持容器和宿主机的时间同步。
healthcheck 选项:
test: ["CMD-SHELL", "curl -f http://localhost/ || exit 1"]:检查容器是否正常启动,通过访问容器的根路径(/)并检查返回的状态码是否为200。interval: 30s:检查间隔为30秒。timeout: 10s:超时时间为10秒。retries: 3:检查失败重试3次。start_period: 5s:容器启动后等待5秒再开始检查。
常用命令
不指定 compose.yaml 文件
shell
# 进入存放 compose.yaml 文件的目录
cd /opt/nginx
docker compose up -d
docker compose restart
docker compose down
docker compose logs -f指定 compose.yaml 文件
shell
docker compose -f /opt/nginx/compose.yaml up -d
docker compose -f /opt/nginx/compose.yaml restart
docker compose -f /opt/nginx/compose.yaml down
docker compose -f /opt/nginx/compose.yaml logs -f