Docker 컨테이너의 SSL에 대한 과제는 아무도 이야기하지 않습니다.
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는 다음을 수행합니다.
- 보안 통신을 보장하기 위해 HTTP 요청을 HTTPS로 리디렉션합니다.
- 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











프론트 엔드 개발시 프론트 엔드 열지대 티켓 인쇄를위한 자주 묻는 질문과 솔루션, 티켓 인쇄는 일반적인 요구 사항입니다. 그러나 많은 개발자들이 구현하고 있습니다 ...

기술 및 산업 요구에 따라 Python 및 JavaScript 개발자에 대한 절대 급여는 없습니다. 1. 파이썬은 데이터 과학 및 기계 학습에서 더 많은 비용을 지불 할 수 있습니다. 2. JavaScript는 프론트 엔드 및 풀 스택 개발에 큰 수요가 있으며 급여도 상당합니다. 3. 영향 요인에는 경험, 지리적 위치, 회사 규모 및 특정 기술이 포함됩니다.

JavaScript는 현대 웹 개발의 초석이며 주요 기능에는 이벤트 중심 프로그래밍, 동적 컨텐츠 생성 및 비동기 프로그래밍이 포함됩니다. 1) 이벤트 중심 프로그래밍을 사용하면 사용자 작업에 따라 웹 페이지가 동적으로 변경 될 수 있습니다. 2) 동적 컨텐츠 생성을 사용하면 조건에 따라 페이지 컨텐츠를 조정할 수 있습니다. 3) 비동기 프로그래밍은 사용자 인터페이스가 차단되지 않도록합니다. JavaScript는 웹 상호 작용, 단일 페이지 응용 프로그램 및 서버 측 개발에 널리 사용되며 사용자 경험 및 크로스 플랫폼 개발의 유연성을 크게 향상시킵니다.

동일한 ID로 배열 요소를 JavaScript의 하나의 객체로 병합하는 방법은 무엇입니까? 데이터를 처리 할 때 종종 동일한 ID를 가질 필요가 있습니다 ...

JavaScript를 배우는 것은 어렵지 않지만 어려운 일입니다. 1) 변수, 데이터 유형, 기능 등과 같은 기본 개념을 이해합니다. 2) 마스터 비동기 프로그래밍 및 이벤트 루프를 통해이를 구현하십시오. 3) DOM 운영을 사용하고 비동기 요청을 처리합니다. 4) 일반적인 실수를 피하고 디버깅 기술을 사용하십시오. 5) 성능을 최적화하고 모범 사례를 따르십시오.

이 기사에서 시차 스크롤 및 요소 애니메이션 효과 실현에 대한 토론은 Shiseido 공식 웹 사이트 (https://www.shiseido.co.jp/sb/wonderland/)와 유사하게 달성하는 방법을 살펴볼 것입니다.

Console.log 출력의 차이의 근본 원인에 대한 심층적 인 논의. 이 기사에서는 Console.log 함수의 출력 결과의 차이점을 코드에서 분석하고 그에 따른 이유를 설명합니다. � ...

JavaScript의 최신 트렌드에는 Typescript의 Rise, 현대 프레임 워크 및 라이브러리의 인기 및 WebAssembly의 적용이 포함됩니다. 향후 전망은보다 강력한 유형 시스템, 서버 측 JavaScript 개발, 인공 지능 및 기계 학습의 확장, IoT 및 Edge 컴퓨팅의 잠재력을 포함합니다.
