Docker 컨테이너의 SSL에 대한 과제는 아무도 이야기하지 않습니다.

Mary-Kate Olsen
풀어 주다: 2024-10-06 18:38:03
원래의
732명이 탐색했습니다.

The Challenge About SSL in Docker Containers No One Talks About

Docker 환경에서 SSL을 설정하는 데 어려움을 겪어보신 적이 있으신가요? SSL은 많은 사람들에게 위협적인 장애물이 될 수 있지만 특히 인터넷에 노출된 경우 애플리케이션을 보호하는 것이 중요합니다. 이 게시물에서는 Dockerized 설정에서 Let's Encrypt SSL 생성을 위해 Nginx 및 Certbot을 추가하는 방법을 안내하겠습니다. 이를 통해 인증서를 자동으로 갱신하고 번거로움을 최소화하면서 환경을 안전하게 유지할 수 있습니다.

들어가자!

전제 조건

  • 컴퓨터에 Docker와 Docker Compose가 설치되어 있습니다.
  • Docker Compose와 Nginx에 대한 기본 이해
  • 귀하의 서버를 가리키는 도메인 이름입니다.

이 예에서는 Nginx를 역방향 프록시로 사용하고 Certbot을 사용하여 SSL 인증서를 관리합니다. 아래에는 docker-compose.yml, Nginx 자동 다시 로드를 위한 셸 스크립트, 모든 설정에 필요한 구성 파일이 있습니다.

Docker 작성 구성

먼저 Nginx와 Certbot을 설정하기 위한 Docker Compose 구성을 보여드리겠습니다.


# docker-compose.yml

services:
  nginx:
    container_name: nginx
    image: nginx:latest
    restart: unless-stopped
    env_file: .env
    networks:
      - your-app-network # Update this with your application service network
    ports:
      - 80:80
      - 443:443
    depends_on:
      - your-app # Your application service
    volumes:
      - ./nginx/secure/:/etc/nginx/templates/
      - /etc/localtime:/etc/localtime:ro
      - ./nginx/certbot/conf:/etc/letsencrypt
      - ./nginx/certbot/www:/var/www/certbot
      - ./nginx/99-autoreload.sh:/docker-entrypoint.d/99-autoreload.sh  # Script to autoreload Nginx when certs are renewed

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


로그인 후 복사

이 Docker Compose 파일은 두 가지 서비스를 정의합니다.

  • Nginx: 역방향 프록시 역할을 하며 백엔드에 요청을 처리합니다.
  • Certbot: Let's Encrypt를 사용하여 SSL 인증서 생성 및 갱신을 관리합니다.

Certbot 서비스는 무한 루프로 실행되어 12시간마다 인증서를 갱신합니다. 인증서는 공유 볼륨(./nginx/certbot/conf)에 저장되므로 Nginx가 최신 인증서 파일에 액세스할 수 있습니다.

Nginx 구성

Nginx는 HTTP 및 HTTPS 트래픽을 모두 처리하는 역방향 프록시 역할을 합니다. 초기 요청의 경우 Certbot은 도메인 확인 프로세스를 완료하기 위해 HTTP(포트 80)가 필요합니다.


# default.conf.template

server {
    listen 80;
    server_name ${APP_DOMAIN};

    location / {
        return 301 https://$host$request_uri;
    }

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }
}

server {
    listen 443 ssl;
    server_name ${APP_DOMAIN};
    server_tokens off;
    client_max_body_size 20M;

    ssl_certificate /etc/letsencrypt/live/${APP_DOMAIN}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/${APP_DOMAIN}/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    location / {
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Url-Scheme $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://my-app:3000; // Your app service name
    }
}


로그인 후 복사

위 구성 파일에서 Nginx는 다음을 수행합니다.

  1. 보안 통신을 보장하기 위해 HTTP 요청을 HTTPS로 리디렉션합니다.
  2. SSL 종료를 처리하고 백엔드 서비스(예: my-app:3000)에 대한 요청을 프록시합니다.

Nginx 구성 자동 다시 로드

SSL 인증서가 갱신된 후 업데이트된 인증서를 적용하려면 Nginx를 다시 로드해야 합니다. 이 프로세스를 자동화하려면 간단한 자동 다시 로드 스크립트를 추가하세요.


# 99-autoreload.sh

#!/bin/sh
while :; do
    # Optional: Instead of sleep, detect config changes and only reload if necessary.
    sleep 6h
    nginx -t && nginx -s reload
done &


로그인 후 복사

이 스크립트는 Nginx 컨테이너 내에서 실행되며 6시간마다 또는 인증서가 갱신될 때마다 Nginx를 다시 로드합니다.

환경 변수

Certbot 등록을 위해 도메인 이름과 이메일 주소를 저장할 .env 파일을 생성하세요.


# .env file

APP_DOMAIN=your-domain.com
SSL_EMAIL=contact@your-domain.com


로그인 후 복사

초기 SSL 인증서 생성

Nginx가 HTTPS 트래픽을 제공하려면 먼저 초기 SSL 인증서를 생성해야 합니다. SSL 인증서를 생성하려면 다음 bash 스크립트(init-letsencrypt.sh)를 사용하십시오.


#!/bin/bash

# Source the .env file
if [ -f .env ]; then
  export $(grep -v '^#' .env | xargs)
fi

if ! [ -x "$(command -v docker compose)" ]; then
    echo 'Error: docker compose is not installed.' >&2
    exit 1
fi

domains=(${APP_DOMAIN:-example.com})
rsa_key_size=4096
data_path="./nginx/certbot"
email="${SSL_EMAIL:-hello@example.com}" # Adding a valid address is strongly recommended
staging=0 # Set to 1 if you're testing your 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/_internal/tls_configs/options-ssl-nginx.conf >"$data_path/conf/options-ssl-nginx.conf"
    curl -s https://raw.githubusercontent.com/certbot/certbot/master/certbot/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 -f "docker-compose.yml" run --rm --entrypoint "\
  openssl req -x509 -nodes -newkey rsa:$rsa_key_size -days 1\
    -keyout '$path/privkey.pem' \
    -out '$path/fullchain.pem' \
    -subj '/CN=localhost'" certbot
echo

echo "### Starting nginx ..."
docker compose  -f "docker-compose.yml" up --force-recreate -d nginx
echo

echo "### Deleting dummy certificate for $domains ..."
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 -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 -f "docker-compose.yml" exec nginx nginx -s reload



로그인 후 복사

요약

요약하자면 위에 제공된 구성은 Nginx를 Dockerized 애플리케이션의 역방향 프록시로 설정하고 Let's Encrypt SSL 인증서는 Certbot에서 자동으로 관리합니다. 이 설정을 사용하면 SSL을 수동으로 갱신할 필요 없이 애플리케이션에 대한 보안 연결이 보장됩니다.

최종 메모

처음으로 환경을 불러오려면 다음을 사용하세요.


chmod a+x init-letsencrypt.sh
./init-letsencrypt.sh


로그인 후 복사

다음과 같은 경우 일반적인 docker compose 명령을 사용하여 환경을 불러올 수 있습니다.


docker-compose up -d


로그인 후 복사

도메인이 서버를 가리키고 HTTP 및 HTTPS 트래픽에 대한 액세스를 허용하려면 포트 80과 443이 열려 있는지 확인하세요.

문제가 발생하거나 개선을 위한 제안 사항이 있으면 아래 댓글로 알려주시기 바랍니다! 특정 주제에 대한 문제 해결이나 확장에 도움을 드리게 되어 기쁘게 생각합니다.

위 내용은 Docker 컨테이너의 SSL에 대한 과제는 아무도 이야기하지 않습니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!