DevOps/Docker

Docker Nginx Certbot SSL 인증서 받는 1가지 방법

kimc 2023. 11. 21. 11:56
반응형

One way to obtain Docker Nginx Certbot SSL certificates

 


```

도커 엔진스 서트봇 에스에스엘 인증서 발급받는 방법

```

이번 글을 통해 배워갈 내용

1. 도커, 도커 컴포즈 설치

2. 도커 샘플 헬로 월드 이미지 실행

3. 헬로 월드 이미지에 대해서 인증서 발급


도커 설치

시스템 업데이트

apt-get update
apt-get upgrade

 

도커 설치

curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh

 

(도커설치 관련글)

https://codemasterkimc.tistory.com/674

 

우분투에 도커 설치하는 두가지 방법

``` 우분투에 도커 설치하는 두 가지 방법 ``` 이번 글을 통해 배워갈 내용 도커 설치 방법 1 도커 설치 방법 2 Glossary 도커 설치 방법 1 방법1은 간단한 방법으로 Production에는 권장은 되지 않습니다

codemasterkimc.tistory.com

 

도커 컴포즈 설치

설치

sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

권한 부여

sudo chmod +x /usr/local/bin/docker-compose

 

설치 확인

docker-compose --version

 

 


샘플 이미지 실행(선택)

원하는 위치에 compose.yaml 파일 생성

nano compose.yaml

 

샘플이미지 세팅( compose.yaml 내부)

services:
    helloworld:
        container_name: helloworld
        image: crccheck/hello-world
        ports:
          - 80:8000

 

샘플 이미지 실행

docker compose up -d helloworld

 

테스트

curl localhost
curl -I localhost

 

샘플 이미지 설명
https://github.com/crccheck/docker-hello-world

 

GitHub - crccheck/docker-hello-world: Hello World web server in under 2 MB

Hello World web server in under 2 MB . Contribute to crccheck/docker-hello-world development by creating an account on GitHub.

github.com


nginx.conf  세팅

원하는 위치에 nginx.conf 파일 생성

mkdir -p ./nginx
nano ./nginx/nginx.conf

 

nginx.conf 파일 세팅

events {
    worker_connections  1024;
}

http {
    server_tokens off;
    charset utf-8;

    server {
        listen 80 default_server;

        server_name _;

        location / {
            proxy_pass http://helloworld:8000/;
        }
    }
}

 

nginx 세팅 및 실행

compose.yaml에 nginx 추가

nano compose.yaml
services:
    helloworld:
        container_name: helloworld
        image: crccheck/hello-world
        expose:
            - 8000

    nginx:
        container_name: nginx
        restart: unless-stopped
        image: nginx
        ports:
            - 80:80
            - 443:443
        volumes:
            - ./nginx/nginx.conf:/etc/nginx/nginx.conf

 

nxginx 실행

docker compose up -d nginx


Certbot 설정

nano ./nginx/nginx.conf

아래 내용 추가

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

 

따라서 아래와 같이 설정

events {
    worker_connections  1024;
}

http {
    server_tokens off;
    charset utf-8;

    server {
        listen 80 default_server;

        server_name _;

        location / {
            proxy_pass http://helloworld:8000/;
        }

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

 

경로 생성

mkdir -p ./certbot/conf
mkdir -p ./certbot/www

 

compose.yaml 설정

 

nano compose.yaml
    helloworld:
        container_name: helloworld
        image: crccheck/hello-world
        expose:
            - 8000

    nginx:
        container_name: nginx
        restart: unless-stopped
        image: nginx
        ports:
            - 80:80
            - 443:443
        volumes:
            - ./nginx/nginx.conf:/etc/nginx/nginx.conf
            - ./certbot/conf:/etc/letsencrypt
            - ./certbot/www:/var/www/certbot

    certbot:
        image: certbot/certbot
        container_name: certbot
        volumes:
           - ./certbot/conf:/etc/letsencrypt
           - ./certbot/www:/var/www/certbot
        command: certonly --webroot -w /var/www/certbot --force-renewal --email {email} -d {domain} --agree-tos

 

nginx 재시작 후

certbot 인증 시작

docker compose restart nginx

docker compose up -d certbot

 

인증이 잘되었는지 확인

docker logs certbot

 


변경된 인증서 설정 적용

nginx.conf 수정

nano ./nginx/nginx.conf

 

{domain}을 지우고 해당 위치들에 서버 주소 입력

예시) www.nxver.com 
필요시 CORS 세팅 처리

events {
    worker_connections  1024;
}

http {
    server_tokens off;
    charset utf-8;

    # always redirect to https
    server {
        listen 80 default_server;

        server_name _;

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

    server {
        listen 443 ssl http2;
        # use the certificates
        ssl_certificate     /etc/letsencrypt/live/{domain}/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/{domain}/privkey.pem;
        server_name {domain};
        root /var/www/html;
        index index.php index.html index.htm;

        location / {
            proxy_pass http://helloworld:8000/;
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, PATCH, DELETE, OPTIONS';
            add_header 'Access-Control-Allow-Headers' '*';
            add_header 'Access-Control-Expose-Headers' 'Content-Length, Content-Range';
            add_header 'Access-Control-Allow-Credentials' 'true';
        }

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

 

docker nginx 재시작

docker compose restart nginx

 

필요시 아래와 같이 세팅하고 nginx 재시작해도 무방함

events {
    worker_connections  1024;
}

http {
    server_tokens off;
    charset utf-8;

    # always redirect to https
    server {
        listen 80 default_server;

        server_name _;

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

    server {
        listen 443 ssl http2;
        # use the certificates
        ssl_certificate     /etc/letsencrypt/live/{domain}/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/{domain}/privkey.pem;
        server_name {domain};
        root /var/www/html;
        index index.php index.html index.htm;

        location / {
            proxy_redirect off;
            proxy_pass http://{container name}:5000;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
        }

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

 

 


기타

ufw 방화벽 처리

sudo ufw allow 80/tcp comment 'Nginx HTTP'
sudo ufw allow 443/tcp comment 'Nginx HTTPS'
sudo ufw status
sudo ufw enable

 

인증서 자동갱신

 

shell script 생성

mkdir /scripts
nano /scripts/renew_and_restart.sh

 

script 내용

docker-compose 파일이 /hello 경로에 있다고 가

#!/bin/bash
# Navigate to the directory
cd /hello
# Bring up certbot and wait for it to complete
docker compose up -d certbot
# Assuming certbot runs in detached mode, wait a bit to ensure completion. Adjust sleep as necessary.
sleep 60
# Restart nginx to apply the new certificates
docker compose restart nginx

 

권한 부여

chmod +x /scripts/renew_and_restart.sh

 

크론부여

매월 1일 오전 3시에 실행

crontab -e
0 3 1 * * /scripts/renew_and_restart.sh
crontab -l

 

 


참조 및 인용

https://certbot.eff.org/instructions?ws=nginx&os=ubuntufocal

 

Certbot Instructions

Tagline

certbot.eff.org

 

https://eff-certbot.readthedocs.io/en/stable/install.html#running-with-docker

 

Get Certbot — Certbot 2.6.0 documentation

Note Certbot is most useful when run with root privileges, because it is then able to automatically configure TLS/SSL for Apache and nginx. Certbot is meant to be run directly on a web server, normally by a system administrator. In most cases, running Cert

eff-certbot.readthedocs.io

 

https://www.programonaut.com/setup-ssl-with-docker-nginx-and-lets-encrypt/

 

Setup SSL with Docker, NGINX and Lets Encrypt

In this guide you will learn how to secure your web app with SSL by utilizing Docker, NGINX and Lets Encrypt.

www.programonaut.com


 

읽어주셔서 감사합니다

 

무엇인가 얻어가셨기를 바라며

 

오늘도 즐거운 코딩 하시길 바랍니다 ~ :)

 

 

반응형