Docker 下使用 nginx 自动更新 LetsEncrypt 证书

Docker 下使用 nginx 自动更新 LetsEncrypt 证书

我在设置 LetsEncrypt 证书自动更新时遇到了麻烦。

我在为 Django 应用程序提供服务的 Docker 容器下运行 nginx。

这是我的 docker-compose 文件:

version: '3.8'

services:
  app:
    image: registry.myimage.app
    restart: always
    build:
      context: .
      dockerfile: ./app/Dockerfile
    ports:
      - "8000:8000"
    command: /start
    expose:
      - 8000
    env_file:
      - .env

  nginx:
    image: registry.myimage.nginx:latest
    build: .app/nginx
    restart: unless-stopped
    volumes:
      - /etc/letsencrypt:/etc/letsencrypt
    ports:
      - "80:80"
      - "443:443"
    depends_on:
      - app
    command: "/bin/sh -c 'while :; do sleep 6h & wait $${!}; nginx -s reload; done & nginx -g \"daemon off;\"'"

  certbot:
    image: certbot/certbot
    restart: unless-stopped
    volumes:
      - /etc/letsencrypt:/etc/letsencrypt
    command: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'"

volumes:
  app:

和我的nginx.conf文件:

upstream django {
    server app:8000;
}

server {
    listen 80;
    listen [::]:80;
    server_name www.mywebsite.com mywebsite.com;

    location ^~ /.well-known/acme-challenge/ {
        root /var/www/html;
    }

    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name mywebsite.com www.mywebsite.com;

    # SSL
    ssl_certificate /etc/letsencrypt/live/mywebsite.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/mywebsite.com/privkey.pem;

    ssl_session_cache shared:le_nginx_SSL:10m;
    ssl_session_timeout 1440m;
    ssl_session_tickets off;

    client_max_body_size 4G;
    keepalive_timeout 5;

    location = /favicon.ico { access_log off; log_not_found off; }
    location / {
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;
          proxy_set_header Host $http_host;
          proxy_redirect off;
          proxy_pass http://django;
        }

    location /static/ {
        alias /vol/web/static/;
    }

    location /media/ {
        alias /vol/web/media/;
    }
}

server {
    if ($host = www.mywebsite.com) {
        return 301 https://mywebsite.com$request_uri;
    }


    if ($host = mywebsite.com) {
        return 301 https://mywebsite.com$request_uri;
    }


    listen 80;
    server_name mywebsite.com www.mywebsite.com;
    return 404;

}

server {
    listen 443 ssl default_server;

    # SSL
    ssl_certificate /etc/letsencrypt/live/mywebsite.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/mywebsite.com/privkey.pem;

    server_name _;
    return 444;
}

我的配置有什么问题?为什么它不能自动更新我的证书?

PS:请注意,我对 nginx 配置还很陌生,可能会出现一些琐碎的错误。

相关内容