nginx Docker 部署

在 Docker 中运行 Nginx,容器化部署最佳实践

语法

docker run -d -p 80:80 nginx

参数

参数说明示例级别
-p 80:80 端口映射 docker run -p 80:80 -p 443:443 nginx 常用
-v config 挂载配置文件 -v ./nginx.conf:/etc/nginx/nginx.conf:ro 常用
-v html 挂载网站目录 -v ./html:/usr/share/nginx/html:ro 常用
--name 容器名称 --name my-nginx 常用

示例

快速启动

docker run -d --name nginx \
  -p 80:80 \
  -v $(pwd)/html:/usr/share/nginx/html:ro \
  nginx:alpine
alpine 镜像更小(约 40MB)

自定义配置

docker run -d --name nginx \
  -p 80:80 -p 443:443 \
  -v $(pwd)/nginx.conf:/etc/nginx/nginx.conf:ro \
  -v $(pwd)/conf.d:/etc/nginx/conf.d:ro \
  -v $(pwd)/html:/usr/share/nginx/html:ro \
  -v $(pwd)/certs:/etc/ssl/certs:ro \
  nginx:alpine
挂载配置、站点和证书

Docker Compose

# docker-compose.yml
services:
  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./html:/usr/share/nginx/html:ro
    restart: unless-stopped
推荐用 Compose 管理

多阶段构建(前端项目)

# Dockerfile
FROM node:18-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
构建前端 + Nginx 部署一体化

常见错误

容器启动后立即退出 检查配置文件语法:docker run --rm nginx nginx -t -c /etc/nginx/nginx.conf

技巧

相关命令