Nginx Docker部署 #

一、Docker基础 #

1.1 获取Nginx镜像 #

bash
docker pull nginx:latest
docker pull nginx:1.24
docker pull nginx:alpine

1.2 镜像版本说明 #

标签 说明
latest 最新稳定版
1.24 指定版本
alpine Alpine版本(更小)
mainline 开发版

1.3 查看镜像信息 #

bash
docker images nginx
docker inspect nginx:latest

二、基本运行 #

2.1 最简运行 #

bash
docker run --name my-nginx -p 80:80 -d nginx

2.2 挂载配置文件 #

bash
docker run --name my-nginx \
    -p 80:80 \
    -v /path/to/nginx.conf:/etc/nginx/nginx.conf:ro \
    -d nginx

2.3 挂载多个目录 #

bash
docker run --name my-nginx \
    -p 80:80 \
    -p 443:443 \
    -v /path/to/nginx.conf:/etc/nginx/nginx.conf:ro \
    -v /path/to/conf.d:/etc/nginx/conf.d:ro \
    -v /path/to/html:/usr/share/nginx/html:ro \
    -v /path/to/ssl:/etc/nginx/ssl:ro \
    -v /path/to/logs:/var/log/nginx \
    -d nginx

2.4 目录说明 #

容器路径 说明
/etc/nginx/nginx.conf 主配置文件
/etc/nginx/conf.d/ 额外配置目录
/usr/share/nginx/html 默认根目录
/var/log/nginx 日志目录
/etc/nginx/ssl SSL证书目录

三、Docker Compose #

3.1 基本配置 #

yaml
version: '3.8'

services:
  nginx:
    image: nginx:latest
    container_name: my-nginx
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./html:/usr/share/nginx/html:ro
      - ./logs:/var/log/nginx
    restart: always

3.2 完整配置 #

yaml
version: '3.8'

services:
  nginx:
    image: nginx:1.24-alpine
    container_name: my-nginx
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./conf.d:/etc/nginx/conf.d:ro
      - ./html:/usr/share/nginx/html:ro
      - ./ssl:/etc/nginx/ssl:ro
      - ./logs:/var/log/nginx
    environment:
      - TZ=Asia/Shanghai
    networks:
      - frontend
    depends_on:
      - backend
    restart: always
    healthcheck:
      test: ["CMD", "nginx", "-t"]
      interval: 30s
      timeout: 10s
      retries: 3

  backend:
    image: node:18-alpine
    container_name: my-backend
    working_dir: /app
    volumes:
      - ./app:/app
    command: npm start
    networks:
      - frontend
      - backend
    restart: always

networks:
  frontend:
  backend:

3.3 启动和管理 #

bash
docker-compose up -d
docker-compose down
docker-compose restart
docker-compose logs -f nginx
docker-compose exec nginx nginx -s reload

四、自定义镜像 #

4.1 Dockerfile示例 #

dockerfile
FROM nginx:1.24-alpine

LABEL maintainer="admin@example.com"

RUN apk add --no-cache tzdata && \
    cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
    echo "Asia/Shanghai" > /etc/timezone && \
    apk del tzdata

COPY nginx.conf /etc/nginx/nginx.conf
COPY conf.d /etc/nginx/conf.d
COPY html /usr/share/nginx/html
COPY ssl /etc/nginx/ssl

RUN mkdir -p /var/log/nginx && \
    chown -R nginx:nginx /var/log/nginx

EXPOSE 80 443

CMD ["nginx", "-g", "daemon off;"]

4.2 构建镜像 #

bash
docker build -t my-nginx:1.0 .

4.3 多阶段构建 #

dockerfile
FROM node:18-alpine AS builder

WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

FROM nginx:1.24-alpine

COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]

五、Kubernetes部署 #

5.1 ConfigMap #

yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-config
data:
  nginx.conf: |
    user nginx;
    worker_processes auto;
    error_log /var/log/nginx/error.log;
    
    events {
        worker_connections 1024;
    }
    
    http {
        include /etc/nginx/mime.types;
        default_type application/octet-stream;
        
        server {
            listen 80;
            server_name localhost;
            
            location / {
                root /usr/share/nginx/html;
                index index.html;
            }
        }
    }

5.2 Deployment #

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.24
        ports:
        - containerPort: 80
        volumeMounts:
        - name: nginx-config
          mountPath: /etc/nginx/nginx.conf
          subPath: nginx.conf
        - name: nginx-html
          mountPath: /usr/share/nginx/html
        resources:
          requests:
            cpu: 100m
            memory: 128Mi
          limits:
            cpu: 500m
            memory: 512Mi
        livenessProbe:
          httpGet:
            path: /
            port: 80
          initialDelaySeconds: 10
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /
            port: 80
          initialDelaySeconds: 5
          periodSeconds: 5
      volumes:
      - name: nginx-config
        configMap:
          name: nginx-config
      - name: nginx-html
        emptyDir: {}

5.3 Service #

yaml
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  type: LoadBalancer
  selector:
    app: nginx
  ports:
  - port: 80
    targetPort: 80

5.4 Ingress #

yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: nginx-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - host: example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: nginx-service
            port:
              number: 80

六、高级配置 #

6.1 环境变量 #

yaml
services:
  nginx:
    image: nginx:latest
    environment:
      - TZ=Asia/Shanghai
      - NGINX_HOST=example.com
      - NGINX_PORT=80

在配置中使用:

nginx
server {
    listen ${NGINX_PORT};
    server_name ${NGINX_HOST};
}

6.2 使用envsubst #

yaml
services:
  nginx:
    image: nginx:latest
    environment:
      - NGINX_HOST=example.com
    volumes:
      - ./nginx.conf.template:/etc/nginx/templates/nginx.conf.template:ro
    entrypoint: /bin/sh -c "envsubst < /etc/nginx/templates/nginx.conf.template > /etc/nginx/nginx.conf && nginx -g 'daemon off;'"

6.3 日志驱动 #

yaml
services:
  nginx:
    image: nginx:latest
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"

6.4 资源限制 #

yaml
services:
  nginx:
    image: nginx:latest
    deploy:
      resources:
        limits:
          cpus: '0.5'
          memory: 512M
        reservations:
          cpus: '0.1'
          memory: 128M

七、反向代理配置 #

7.1 代理后端服务 #

yaml
version: '3.8'

services:
  nginx:
    image: nginx:latest
    ports:
      - "80:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    depends_on:
      - app1
      - app2
    networks:
      - frontend

  app1:
    image: node:18-alpine
    working_dir: /app
    volumes:
      - ./app1:/app
    command: npm start
    networks:
      - frontend

  app2:
    image: node:18-alpine
    working_dir: /app
    volumes:
      - ./app2:/app
    command: npm start
    networks:
      - frontend

networks:
  frontend:

nginx.conf:

nginx
upstream backend {
    server app1:3000;
    server app2:3000;
}

server {
    listen 80;
    
    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

八、SSL配置 #

8.1 挂载证书 #

yaml
services:
  nginx:
    image: nginx:latest
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./ssl:/etc/nginx/ssl:ro

8.2 使用Let’s Encrypt #

yaml
version: '3.8'

services:
  nginx:
    image: nginx:latest
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./certbot/conf:/etc/letsencrypt:ro
      - ./certbot/www:/var/www/certbot:ro

  certbot:
    image: certbot/certbot
    volumes:
      - ./certbot/conf:/etc/letsencrypt
      - ./certbot/www:/var/www/certbot
    entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'"

九、监控配置 #

9.1 Prometheus监控 #

yaml
services:
  nginx:
    image: nginx:latest
    ports:
      - "80:80"
      - "9113:9113"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro

  nginx-exporter:
    image: nginx/nginx-prometheus-exporter:latest
    ports:
      - "9113:9113"
    command:
      - '-nginx.scrape-uri=http://nginx/nginx_status'

9.2 日志收集 #

yaml
services:
  nginx:
    image: nginx:latest
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    logging:
      driver: "fluentd"
      options:
        fluentd-address: localhost:24224
        tag: nginx.access

十、完整配置示例 #

yaml
version: '3.8'

services:
  nginx:
    image: nginx:1.24-alpine
    container_name: nginx-proxy
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./nginx/conf.d:/etc/nginx/conf.d:ro
      - ./nginx/html:/usr/share/nginx/html:ro
      - ./nginx/ssl:/etc/nginx/ssl:ro
      - ./nginx/logs:/var/log/nginx
    environment:
      - TZ=Asia/Shanghai
    networks:
      - frontend
    depends_on:
      - backend
    restart: always
    healthcheck:
      test: ["CMD", "wget", "-q", "--spider", "http://localhost/health"]
      interval: 30s
      timeout: 10s
      retries: 3
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"
    deploy:
      resources:
        limits:
          cpus: '1'
          memory: 512M

  backend:
    image: node:18-alpine
    container_name: backend-app
    working_dir: /app
    volumes:
      - ./app:/app
    command: npm start
    environment:
      - NODE_ENV=production
    networks:
      - frontend
      - backend
    restart: always

  redis:
    image: redis:7-alpine
    container_name: redis
    networks:
      - backend
    restart: always

networks:
  frontend:
    driver: bridge
  backend:
    driver: bridge

十一、常用命令 #

bash
docker run --name nginx -p 80:80 -d nginx
docker exec nginx nginx -t
docker exec nginx nginx -s reload
docker logs -f nginx
docker-compose up -d
docker-compose down
docker-compose restart nginx
docker-compose exec nginx nginx -s reload
docker-compose logs -f nginx
docker build -t my-nginx:1.0 .
docker push my-nginx:1.0

十二、总结 #

本章我们学习了:

  1. Docker基础:镜像获取和基本运行
  2. 配置挂载:配置文件、静态文件、日志
  3. Docker Compose:多服务编排
  4. 自定义镜像:Dockerfile编写
  5. Kubernetes部署:Deployment、Service、Ingress
  6. 高级配置:环境变量、日志驱动、资源限制
  7. SSL配置:证书挂载和Let’s Encrypt
  8. 监控配置:Prometheus和日志收集

掌握Docker部署后,让我们进入下一章,学习Lua扩展!

最后更新:2026-03-27