【问题标题】:How to enable HTTPS on AWS EC2 running an NGINX Docker container?如何在运行 NGINX Docker 容器的 AWS EC2 上启用 HTTPS?
【发布时间】:2019-12-05 22:19:54
【问题描述】:

我在 AWS 上有一个运行 Amazon Linux 2 的 EC2 实例。

在它上面,我安装了 Git、docker 和 docker-compose。完成后,我克隆了我的存储库并运行 docker-compose up 以启动我的生产环境。我去公共 DNS,它可以工作。

我现在想在网站上启用 HTTPS。

我的项目有一个使用 React 在 Nginx-alpine 服务器上运行的前端。后端是 NodeJS 服务器。

这是我的 nginx.conf 文件:

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri /index.html;
    }

    location /api/ {
        proxy_pass http://${PROJECT_NAME}_backend:${NODE_PORT}/;
    }    

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

这是我的 docker-compose.yml 文件:

version: "3.7"
services:
##############################
# Back-End Container
##############################
  backend: # Node-Express backend that acts as an API.
    container_name: ${PROJECT_NAME}_backend
    init: true
    build:
      context: ./backend/
      target: production
    restart: always
    environment:
      - NODE_PATH=${EXPRESS_NODE_PATH}
      - AWS_REGION=${AWS_REGION}
      - NODE_ENV=production
      - DOCKER_BUILDKIT=1
      - PORT=${NODE_PORT}
    networks:
      - client
##############################
# Front-End Container
##############################
  nginx:
    container_name: ${PROJECT_NAME}_frontend
    build:
      context: ./frontend/
      target: production
      args:
        - NODE_PATH=${REACT_NODE_PATH}
        - SASS_PATH=${SASS_PATH}
    restart: always
    environment:
      - PROJECT_NAME=${PROJECT_NAME}
      - NODE_PORT=${NODE_PORT}
      - DOCKER_BUILDKIT=1
    command: /bin/ash -c "envsubst '$$PROJECT_NAME $$NODE_PORT' < /etc/nginx/conf.d/nginx.template > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'"
    expose:
      - "80"
    ports:
      - "80:80"
    depends_on:
      - backend
    networks:
      - client
##############################
# General Config
##############################
networks:
  client:

我知道有一个用于 certbot 的 Docker 映像,但我不确定如何使用它。我还担心我通过 http 将请求代理到 /api/ 到服务器的方式。这也会给我带来任何问题吗?


编辑:

尝试 #1:Traefik

我创建了一个 Traefik 容器来通过 HTTPS 路由所有流量。

version: '2'

services:
  traefik:
    image: traefik
    restart: always
    ports:
      - 80:80
      - 443:443
    networks:
      - web
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - /opt/traefik/traefik.toml:/traefik.toml
      - /opt/traefik/acme.json:/acme.json
    container_name: traefik

networks:
  web:
    external: true

对于 toml 文件,我添加了以下内容:

debug = false

logLevel = "ERROR"
defaultEntryPoints = ["https","http"]

[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
    entryPoint = "https"
  [entryPoints.https]
  address = ":443"
  [entryPoints.https.tls]

[retry]

[docker]
endpoint = "unix:///var/run/docker.sock"
domain = "ec2-00-000-000-00.eu-west-1.compute.amazonaws.com"
watch = true
exposedByDefault = false

[acme]
storage = "acme.json"
entryPoint = "https"
onHostRule = true
[acme.httpChallenge]
entryPoint = "http"

我将此添加到我的 docker-compose 生产文件中:

labels:
  - "traefik.docker.network=web"
  - "traefik.enable=true"
  - "traefik.basic.frontend.rule=Host:ec2-00-000-000-00.eu-west-1.compute.amazonaws.com"
  - "traefik.basic.port=80"
  - "traefik.basic.protocol=https"

我为 Traefik 容器运行 docker-compose up,然后在我的生产映像上运行 docker-compose up。我收到以下错误:

无法获得 acme 证书

我正在阅读 Traefik 文档,显然有一种方法可以专门为 Amazon ECS 配置 toml 文件:https://docs.traefik.io/configuration/backends/ecs/

我走对了吗?

【问题讨论】:

    标签: docker nginx amazon-ec2 certbot


    【解决方案1】:

    最简单的方法是设置 ALB 并将其用于 HTTPS。

    1. 创建 ALB
    2. 向 ALB 添加 443 侦听器
    3. 使用 AWS Certificate Manager 生成证书
    4. 将证书设置为负载均衡器的默认证书
    5. 创建目标组
    6. 将您的 EC2 实例添加到目标组
    7. 将 ALB 指向目标组

    将使用带有 https 的 ALB 来处理请求

    【讨论】:

    • 这对我来说效果很好。我要补充的一件事是,在 AWS 中创建负载均衡器时,您必须选择“经典负载均衡器”(也标记为“上一代”),以便允许创建一个只有一个 EC2 实例的负载均衡器。 AWS 现在“鼓励”您选择“Application Load Balancer”,这需要至少 2 个可用区,因此需要 2 个 EC2 实例。
    • 这也适用于我,因为 Application Load Balancer 服务于(当前)只有一个 EC2 实例的 ECS 集群。一个需要注意/很酷的技巧:将 Nginx 设置为仅侦听端口 80,将负载均衡器侦听器(端口 80 和 443)设置为指向目标组,然后在目标组上,仅设置端口目标80(因此,443 没有目标)。这会将 SSL 流量传送到端口 80 上的 Nginx,因此您无需在 Nginx 中配置 SSL 证书 - 它由负载均衡器上的 AWS 证书处理
    【解决方案2】:

    按照Nginx and Let's Encrypt with Docker in Less Than 5 Minutes 上的教程启用 SSL。我在关注它的过程中遇到了一些问题,所以我会在这里澄清一些事情。

    这些步骤包括将以下内容添加到docker-compose.yml:

    ##############################
    # Certbot Container
    ##############################
      certbot:
        image: certbot/certbot:latest
        volumes:
          - ./frontend/data/certbot/conf:/etc/letsencrypt
          - ./frontend/data/certbot/www:/var/www/certbot
    

    至于 docker-compose.yml 的 Nginx 容器 部分,应将其修改为包含添加到 Certbot 容器 的相同卷,以及添加端口并公开配置:

      service_name:
        container_name: container_name
        image: nginx:alpine
        command: /bin/ash -c "exec nginx -g 'daemon off;'"
        volumes:
          - ./data/certbot/conf:/etc/letsencrypt
          - ./data/certbot/www:/var/www/certbot
        expose:
          - "80"
          - "443"
        ports:
          - "80:80"
          - "443:443"
        networks:
          - default
    

    data 文件夹可以保存在其他任何地方,但请确保知道它的位置,并确保在以后重复使用时正确引用它。在此示例中,我只是将其保存在与 docker-compose.yml 文件相同的目录中。

    一旦上述配置到位,将采取几个步骤来初始化证书的颁发。

    首先,您的 Nginx 配置 (default.conf) 将被更改以适应域验证请求:

    server {
        listen       80;
        server_name example.com www.example.com;
        server_tokens off;
    
        location / {
            return 301 https://$server_name$request_uri;
        }
    
        location /.well-known/acme-challenge/ {
            root /var/www/certbot;
        }
    }
    
    server {
         listen 443 ssl;
         server_name example.com www.example.com;
         server_tokens off;
    
         ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
         ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
         include /etc/letsencrypt/options-ssl-nginx.conf;
         ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
    
         location / {
             root   /usr/share/nginx/html;
             index  index.html index.htm;
             try_files $uri /index.html;
             proxy_set_header    Host                $http_host;
             proxy_set_header    X-Real-IP           $remote_addr;
             proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
         }
    }
    

    修改 Nginx 配置文件后,会创建一个虚拟证书以允许进行 Let's Encrypt 验证。有一个脚本可以自动完成所有这些工作,可以使用 CURL 将其下载到项目的根目录中,然后再进行修改以适应环境。还需要使用chmod 命令使脚本可执行:

    curl -L https://raw.githubusercontent.com/wmnnd/nginx-certbot/master/init-letsencrypt.sh > init-letsencrypt.sh && chmod +x init-letsencrypt.sh
    

    脚本下载后,修改如下:

    #!/bin/bash
    
    if ! [ -x "$(command -v docker-compose)" ]; then
      echo 'Error: docker-compose is not installed.' >&2
      exit 1
    fi
    
    -domains=(example.org www.example.org)
    +domains=(example.com www.example.com)
    rsa_key_size=4096
    -data_path="./data/certbot"
    +data_path="./data/certbot"
    -email="" # Adding a valid address is strongly recommended
    +email="admin@example.com" # Adding a valid address is strongly recommended
    staging=0 # Set to 1 when testing setup to avoid hitting request limits
    
    if [ -d "$data_path" ]; then
      read -p "Existing data found for $domains. Continue and replace existing certificate? (y/N) " decision
      if [ "$decision" != "Y" ] && [ "$decision" != "y" ]; then
        exit
      fi
    fi
    
    if [ ! -e "$data_path/conf/options-ssl-nginx.conf" ] || [ ! -e "$data_path/conf/ssl-dhparams.pem" ]; then
      echo "### Downloading recommended TLS parameters ..."
      mkdir -p "$data_path/conf"
      curl -s https://raw.githubusercontent.com/certbot/certbot/master/certbot-nginx/certbot_nginx/tls_configs/options-ssl-nginx.conf > "$data_path/conf/options-ssl-nginx.conf"
      curl -s https://raw.githubusercontent.com/certbot/certbot/master/certbot/ssl-dhparams.pem > "$data_path/conf/ssl-dhparams.pem"
      echo
    fi
    
    echo "### Creating dummy certificate for $domains ..."
    path="/etc/letsencrypt/live/$domains"
    mkdir -p "$data_path/conf/live/$domains"
    -docker-compose run --rm --entrypoint "\
    +docker-compose -f docker-compose.yml run --rm --entrypoint "\
      openssl req -x509 -nodes -newkey rsa:1024 -days 1\
        -keyout '$path/privkey.pem' \
        -out '$path/fullchain.pem' \
        -subj '/CN=localhost'" certbot
    echo
    
    echo "### Starting nginx ..."
    -docker-compose up --force-recreate -d nginx
    +docker-compose -f docker-compose.yml up --force-recreate -d service_name
    echo
    
    echo "### Deleting dummy certificate for $domains ..."
    -docker-compose run --rm --entrypoint "\
    +docker-compose -f docker-compose.yml run --rm --entrypoint "\
      rm -Rf /etc/letsencrypt/live/$domains && \
      rm -Rf /etc/letsencrypt/archive/$domains && \
      rm -Rf /etc/letsencrypt/renewal/$domains.conf" certbot
    echo
    
    echo "### Requesting Let's Encrypt certificate for $domains ..."
    #Join $domains to -d args
    domain_args=""
    for domain in "${domains[@]}"; do
      domain_args="$domain_args -d $domain"
    done
    
    # Select appropriate email arg
    case "$email" in
      "") email_arg="--register-unsafely-without-email" ;;
      *) email_arg="--email $email" ;;
    esac
    
    # Enable staging mode if needed
    if [ $staging != "0" ]; then staging_arg="--staging"; fi
    
    -docker-compose run --rm --entrypoint "\
    +docker-compose -f docker-compose.yml run --rm --entrypoint "\
      certbot certonly --webroot -w /var/www/certbot \
        $staging_arg \
        $email_arg \
        $domain_args \
        --rsa-key-size $rsa_key_size \
        --agree-tos \
        --force-renewal" certbot
    echo
    
    echo "### Reloading nginx ..."
    -docker-compose exec nginx nginx -s reload
    +docker-compose exec service_name nginx -s reload
    

    我确保始终在docker-compose 命令中包含-f 标志,以防万一有人在他们有一个名为docker-compose.yml 的自定义文件时不知道要更改什么。与教程不同,我还确保将服务名称设置为 service_name 以确保区分服务名称和 Nginx 命令。

    注意:如果不确定设置是否正常工作,请确保将暂存设置为 1 以避免达到请求限制。重要的是要记住在测试完成后将其设置回0,并重做修改init-letsencrypt.sh 文件的所有步骤。完成测试并将暂存设置为 0 后,请务必停止以前运行的容器并删除数据文件夹以进行正确的初始认证:

    $ docker-compose -f docker-compose.yml down && yes | docker system prune -a --volumes && sudo rm -rf ./data
    

    一旦证书准备好初始化,脚本将使用sudo 运行;使用 sudo 非常重要,因为如果不使用 sudo 运行,容器内的权限会出现问题。

    $ sudo ./init-letsencrypt.sh
    

    证书颁发后,有自动更新证书的事情;需要做两件事:

    • 在Nginx Container中,Nginx会通过如下修改重新加载新获得的证书:
    service_name:
    ...
    - command: /bin/ash -c "exec nginx -g 'daemon off;'"
    + command: /bin/ash -c "while :; do sleep 6h & wait $${!}; nginx -s reload; done & exec nginx -g 'daemon off;'"
    ...
    
    • 在 Certbot Container 部分中,将添加以下内容以检查证书是否按照 Let's Encrypt 的建议每十二小时更新一次:李>
    certbot:
    ...
    + entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew --webroot -w /var/www/certbot; sleep 12h & wait $${!}; done;'"
    

    在运行docker-compose -f docker-compose.yml up之前,应将data的所有权更改为ec2-user;这是为了避免在运行docker-compose -f docker-compose.yml up或在sudo模式下运行时遇到权限错误:

    sudo chown ec2-user:ec2-user -R /path/to/data/
    

    不要忘记在您的 DNS 提供商中为 Let's Encrypt 添加 CAA 记录。您可以阅读here 了解更多信息。

    如果您在 Nginx 容器中遇到任何问题,因为您正在替换变量并且 $server_name 和 $request_uri 没有正确显示,您可以参考 this issue。

    【讨论】:

    • 嗨@yaharga!在第二个代码块中,您有 container_name: container_name,只是想知道这是前端容器的名称还是其他东西的 container_name。
    • @elco45 只是前端容器的名称。我为 service_name 和 container_name 使用了占位符,因为我试图避免混淆。
    • 请注意,如果您使用 Elastic Beanstalk,此方法将不起作用,因为每次将新的应用程序版本部署到 Elastic Beanstalk 时,配置都会更新,Nginx/Apache 配置会被覆盖
    猜你喜欢
    • 2020-10-04
    • 2020-09-07
    • 2018-01-23
    • 2020-08-03
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 2017-11-19
    相关资源
    最近更新 更多