개발일기

[Re] docker-compose를 통한 ssl 인증 본문

photocard backend server 개발일기

[Re] docker-compose를 통한 ssl 인증

한둥둥 2024. 6. 6. 14:48

 

docker-compose.yml 파일이 위치한 곳에서 conf폴더를 생성한다. 

 

그 후에 vi nginx.conf파일을 아래와 같이 입력한다.

events {
        worker_connections 1024;
}

http {
        server {
                listen 80;

                server_name 도메인입력

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

                }
        }
}

 

docker-compose 파일을 작성하자~!

 

version: "3" # 파일 규격 버전

services: #이 항목 밑에 실행하려는 컨테이너들을 정의
  nginx:
    container_name: nginx
    image: nginx:latest
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./conf/nginx.conf:/etc/nginx/nginx.conf
      - ./data/certbot/conf:/etc/letsencrypt
      - ./data/certbot/www:/var/www/certbot
    environment:
      - VIRTUAL_HOST=도메인
      - TZ=Asia/Seoul
    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:
      - ./data/certbot/conf:/etc/letsencrypt
      - ./data/certbot/www:/var/www/certbot
    entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'"

 

docker-compose 파일은 위에와 같이 작성되어 있다. 

VIRTUAL_HOST에는 도메인을 넣어주자..! 

TimeZone은 서울로 설정해주었다. 

 

위에 파일을 설정 해준 후 docker-compose up -d를 통해서 compose 를 실행 시켜준다. 

그 후에, docker ps 를 통해서 확인하자 

정상적으로 동작하는지 확인하고, 여기서 컨테이너가 종료될 경우, logs를 통해 확인하자.

 

인증서 발급 script 다운로드 및 script를 실행하여 인증서 발급 

 

https://github.com/wmnnd/nginx-certbot/blob/master/init-letsencrypt.sh

 

nginx-certbot/init-letsencrypt.sh at master · wmnnd/nginx-certbot

Boilerplate configuration for nginx and certbot with docker-compose - wmnnd/nginx-certbot

github.com

 

 

인증서를 편하게 발급 받기 위해 아래 curl를 통해서  ./init-letsencrypt를 가져온다. 

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

 

권한을 부여해주자..!

chmod +x init-letsencrypt.sh

 

권한까지 부여했으면 

vi를 통하여 도메인 , 이메일 디렉토리 수정해주자..!

 

 

 

 

#!/bin/bash

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

domains="도메인"
rsa_key_size=4096
data_path="./data/certbot" # 저는 이걸로 패스를 잡아줘서 바꿀 필요는 없었습니다
email="이메일" # 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 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 up --force-recreate -d nginx
echo

echo "### Deleting dummy certificate for $domains ..."
docker-compose 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 "\
  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

준비 완료

 

nginx.conf

events {
    worker_connections 1024;
}

http {
    server {
        listen 80;
        server_name photocard.site www.photocard.site;

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

        location / {
            return 301 https://$host$request_uri;
        }
    }
    server {
        listen 443 ssl;
        server_name photocard.site www.photocard.site;

        ssl_certificate /etc/letsencrypt/live/photocard.site/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/photocard.site/privkey.pem;
        include /etc/letsencrypt/options-ssl-nginx.conf;
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

        location / {
            proxy_pass http://back:8080;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
}

 

 

 

오류 발생 

ERROR: for nginx  'ContainerConfig'

이 오류를 만났을 때, docker-compose volume설정을 잘못해준건가 싶었음.. 하지만 아니였다..! 

도커가 먼가 이상한가 싶어서 아래의 과정을 따라 했다.

 

Docker 업데이트 후, ce다운로드  

sudo apt-get update
sudo apt-get install -y docker-ce docker-ce-cli containerd.io

 

Docker compose 업데이트 

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

 

오류 

nginx: [emerg] unexpected "}" in /etc/nginx/nginx.conf:16

 

{ } 부분 앞에 

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

 

이부분에서 오타를 내버려서 발생했던 오류 이것때문에 한참동안 고생했음...