냐냐한 IT/냐냐한 실습 기록

Nginx + Ubuntu 환경에 certbot 설치

소소하냐 2023. 2. 9. 19:07

보안(HTTPS) 연결을 위해, 

Certbot을 설치해서  Let’s Encrypt 인증서를 무료로 발급받고 

3개월에 한번 인증서를 갱신해줘야하는 불편함을 Certbot이 해주도록 합니다. 

 

설치에 대한 내용은 Certbot 공식 사이트에서 확인할 수 있습니다. 

아래 이미지처럼, 본인 상황에 맞는 Software / System을 선택하여 설치 지침을 확인할 수 있습니다. 

 

본인 상황에 Software / System을 선택하여 설치 지침 확인

 

저는 Software: Nginx, System: Ubuntu 16으로 선택하여 내용을 확인했습니다. 

 

영어로 되어있기 때문에, 저의 기록 용도 및 누군가에게 도움이 되도록 해당 내용을 남겨봅니다. (feat. 구글 번역기)

 


 

필요 사항

  •  command line을 사용할 수 있는 환경
  • 온라인 상에 있는 HTTP 웹 사이트, 80 포트가 열려있어야 합니다.
  • sudo 권한으로 ssh 접근이 가능한 서버에 호스팅되어있어야 합니다. 

 

Nginx, Ubuntu 16 선택 내용 중 일부 캡쳐

 

1. 서버에 연결

HTTP 웹 사이트 서버에 sudo 권한이 있는 사용자 계정으로 SSH로 연결합니다.

 

1. SSH into the server

SSH into the server running your HTTP website as a user with sudo privileges.

 

2. snapd 설치

classic snap 지원을 활성화 하려면 snapd 설치 및 다음 안내를 따라야 합니다.

설치 안내: snapcraft's site to install snapd

 

2. Install snapd

You'll need to install snapd and make sure you follow any instructions to enable classic snap support.

Follow these instructions on snapcraft's site to install snapd

 

2-1. Install snapd 내용 중 Ubuntu 관련

Install snapd 참고 URL 내용 중 일부

 

참고 URL: https://snapcraft.io/docs/installing-snap-on-ubuntu 

 

Ubutu 16.04 LTS 이상일 경우, 이미 설치 되어 있다고 합니다.

그러므로 다음 단계로 넘어갑니다.

 

3. 최신 버전 snapd

command line에 다음 명령어를 실행하여, 최신 버전의 snapd가 되게 합니다.

 

3. Ensure that your version of snapd is up to date

Execute the following instructions on the command line on the machine to ensure that you have the latest version of snapd.

 

sudo snap install core; sudo snap refresh core

 

4. certbot-auto 및 모든 Certbot OS package 제거

apt, dnf, yum 같은 OS package manager를 사용하여 설치된 Certbot 패키지가 있다면, Certbot snap 설치 전에 제거하여, certbot 명령어가 실행될 때 OS package manager가 아닌 snap이 사용되도록 합니다. OS마다 명령어는 다르지만, 일반적인 예는 sudo apt-get remove certbotsudo dnf remove certbot, 또는 sudo yum remove certbot입니다.

 

4. Remove certbot-auto and any Certbot OS packages

If you have any Certbot packages installed using an OS package manager like apt, dnf, or yum, you should remove them before installing the Certbot snap to ensure that when you run the command certbot the snap is used rather than the installation from your OS package manager. The exact command to do this depends on your OS, but common examples are sudo apt-get remove certbot, sudo dnf remove certbot, or sudo yum remove certbot.

 

저의 경우, 따로 설치된 건 없으니 다음 단계로 넘어갑니다.

 

5. Certbot 설치

command line에 다음 명령어를 실행하여 Certbot을 설치합니다.

 

5. Install Certbot

Run this command on the command line on the machine to install Certbot.

 

sudo snap install --classic certbot

 

certbot 설치 명령어 입력

 

6. Certbot 명령어 준비

command line에 다음 명령어를 실행하여 certbot 명령어 실행을 보장합니다.

 

6. Prepare the Certbot command

Execute the following instruction on the command line on the machine to ensure that the certbot command can be run.

 

sudo ln -s /snap/bin/certbot /usr/bin/certbot

 

7. Certbot 실행 방법 선택

인증서 취득과 설치(설정)… 

다음 명령어 실행으로 인증서를 취득 및 Certbot이 자동으로 nginx 구성을 편집하도록 제공됩니다. 단일 단계로 HTTPS 액세스를 켭니다.

 

7. Choose how you'd like to run Certbot

Either get and install your certificates...

Run this command to get a certificate and have Certbot edit your nginx configuration automatically to serve it, turning on HTTPS access in a single step.

 

sudo certbot --nginx

 

인증서만 취득

nginx 구성을 수동으로 구성하려면, 다음 명령어를 실행하세요.

 

Or, just get a certificate

If you're feeling more conservative and would like to make the changes to your nginx configuration by hand, run this command.

sudo certbot certonly --nginx

 

저는 인증서 취득과 설치(설정)까지 해주는 sudo certbot --nginx 명령어를 사용하기로 합니다.  

명령어 입력 전 아래 내용을 확인해 주세요. 

 

!여기서 주의!

/etc/nginx/sites-available/설정파일 내용 중 server_name을 확인하세요. 

 

certbot 실행시, 아래와 같이 도메인 명을 입력하게 됩니다. 

 

"Please enter the domain name(s) you would like on your certificate (comma and/or
space separated) (Enter 'c' to cancel): 도메인"

 

 

입력한 도메인으로 인증서가 발급되고, certbot이 자동으로 nginx 설정을 변경하려고 합니다.

위에서 입력한 도메인과 일치하는 server_name을 찾지만, 해당 도메인이 server_name으로 설정되어 있지 않다면 아래와 같은 오류가 발생합니다. (인증서는 발급되지만, 자동으로 nginx 설정파일을 변경해주지는 않는 결과

 

"Could not automatically find a matching server block for 도메인. Set the `server_name` directive to use the Nginx installer. Ask for help or search for solutions at https://community.letsencrypt.org. See the logfile /var/log/letsencrypt/letsencrypt.log or re-run Certbot with -v for more details."

 

 

/etc/nginx/sites-available/설정파일 내용 중 server_name을 확인하세요: 

server {
        listen 80;
        server_name 도메인;
 
        location / {
                proxy_pass http://localhost:8080;
                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;
        }
}

 

(저는 server_name localhost로 되어있는 상태로 진행해서, 오류가 발생했습니다.) 

 

명령어 실행

sudo certbot --nginx

 

위 명령어를 실행하면, 추가로 입력할 내용들이 있습니다. 

 

  • 갱신 및 보안 알림을 받을 이메일 주소를 입력
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Enter email address (used for urgent renewal and security notices)
 (Enter 'c' to cancel): 갱신 및 보안 알림을 받을 이메일 주소를 입력

 

  • 서비스 약관을 읽고, ACM 서버에 등록 하는 것에 동의하십니까? 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.3-September-21-2022.pdf. You must
agree in order to register with the ACME server. Do you agree?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y

 

  • 인증서가 성공적으로 발급되면, Electronic Frontier Foundation에 이메일 주소를 공유하시겠습니까?
    (본인 선택에 따라 'N'으로 선택해도 될 듯 합니다)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing, once your first certificate is successfully issued, to
share your email address with the Electronic Frontier Foundation, a founding
partner of the Let's Encrypt project and the non-profit organization that
develops Certbot? We'd like to send you email about our work encrypting the web,
EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y

 

  • 인증서 도메인 이름을 입력하세요. (쉼표 또는 띄어쓰기로 구분, 취소하려면 'c' 입력) 
Account registered.
Please enter the domain name(s) you would like on your certificate (comma and/or
space separated) (Enter 'c' to cancel):도메인
Requesting a certificate for 도메인

 

  • 인증서 발급 성공 메세지 및 다음 단계 안내가 표시됩니다. 
Successfully received certificate.
Certificate is saved at: /etc/letsencrypt/live/도메인/fullchain.pem
Key is saved at:         /etc/letsencrypt/live/도메인/privkey.pem
This certificate expires on 2023-05-03.
These files will be updated when the certificate renews.
Certbot has set up a scheduled task to automatically renew this certificate in the background.

Deploying certificate
Could not install certificate

NEXT STEPS:
- The certificate was saved, but could not be installed (installer: nginx). After fixing the error shown below, try installing it again by running:
  certbot install --cert-name 도메인

 

  • 저의 경우, 위에서 설명한 대로 server_name을 도메인으로 변경하지 않아 아래와 같은 실패 메세지가 표시됐습니다.
Could not automatically find a matching server block for 도메인. Set the `server_name` directive to use the Nginx installer.
Ask for help or search for solutions at https://community.letsencrypt.org. See the logfile /var/log/letsencrypt/letsencrypt.log or re-run Certbot with -v for more details.

 

명령어 다시 실행 

이미 인증서는 발급된 상태지만, Nginx 설정을 자동으로 변경하려고 명령어를 다시 실행했습니다. 

 

  • /etc/nginx/sites-available/설정파일 내용 중 server_name을 변경 후 다시 명령어를 입력 합니다. 
sudo certbot --nginx

 

  • HTTPS로 활성화할 도메인을 선택합니다. (모든 도메인을 선택하는 것을 권장합니다.) 쉼표 또는 공백으로 번호를 구분하여 입력하거나 모든 옵션을 선택하려면 빈 값 그대로 둡니다(취소하려면 'c' 입력)
root@...:~# sudo certbot --nginx

Saving debug log to /var/log/letsencrypt/letsencrypt.log

Which names would you like to activate HTTPS for?
We recommend selecting either all domains, or all domains in a VirtualHost/server block.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: 도메인
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate numbers separated by commas and/or spaces, or leave input
blank to select all options shown (Enter 'c' to cancel): 1

 

  • 요청한 도메인 또는 인증서 이름과 동일한 만료가 임박하지 않은 기존 인증서가 있습니다. 1: 기존 인증서를 다시 설치, 2: 인증서 갱신 및 교체 중 어떤 작업을 진행할 지 선택합니다. (저는 1을 선택했습니다.) 
Certificate not yet due for renewal

You have an existing certificate that has exactly the same domains or certificate name you requested and isn't close to expiry.
(ref: /etc/letsencrypt/renewal/도메인.conf)

What would you like to do?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: Attempt to reinstall this existing certificate
2: Renew & replace the certificate (may be subject to CA rate limits)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 1

 

  • 성공을 축하하는 내용이 표시됩니다. 
Deploying certificate
Successfully deployed certificate for 도메인 to /etc/nginx/sites-enabled/site
Congratulations! You have successfully enabled HTTPS on https://도메인

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
If you like Certbot, please consider supporting our work by:
 * Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
 * Donating to EFF:                    https://eff.org/donate-le
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

 

변경된 Nginx 설정 파일 내용 확인

server {
        server_name 도메인;

        location / {
                proxy_pass http://localhost:8080;
                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;
        }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/도메인/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/도메인/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = 도메인) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


        listen 80;
        server_name 도메인;
    return 404; # managed by Certbot


}

 

8. 자동 갱신 테스트

시스템의 Certbot 패키지에는 인증서 만료 전 자동으로 갱신하는 cron job 또는 systemd timer가 함께 있습니다. 구성을 변경하지 않는 한, Certbot을 다시 실행할 필요가 없습니다. 다음 명령어 실행으로 인증서 자동 갱신을 테스트할 수 있습니다:

 

8. Test automatic renewal

The Certbot packages on your system come with a cron job or systemd timer that will renew your certificates automatically before they expire. You will not need to run Certbot again, unless you change your configuration. You can test automatic renewal for your certificates by running this command:

 

sudo certbot renew --dry-run

 

certbot 갱신 명령은 다음 위치 중 하나에 설치됩니다:

 

The command to renew certbot is installed in one of the following locations:

  • /etc/crontab/
  • /etc/cron.*/*
  • systemctl list-timers

 

만료일이 : 2023년 5월 3일으로 되어있으니 그 이후 확인하여 자동 갱신 여부를 확인 후, 내용 추가하도록 하겠습니다. 

 

내용추가 (2023.05.22)

자동 갱신이 되었는지 확인 결과 아래와 같이 2023.04.03 자동 갱신이 된 것을 확인할 수 있었습니다. 

 

자동 갱신 확인

 

9. Certbot 작동 확인 

사이트가 제대로 설정되었는지 확인하려면, 브라우저에 https://당신의-웹사이트URL/을 방문하고 URL 표시줄에서 자물쇠 아이콘을 확인하십시오.

 

9. Confirm that Certbot worked

To confirm that your site is set up properly, visit https://yourwebsite.com/ in your browser and look for the lock icon in the URL bar.

 

(참고로, 방화벽(Naver Cloud ACG)에 80번과 동일하게, 443 포트를 허용해주셔야 합니다.)

 

 

참고 : Certbot - Nginx & Ubuntu16 설치 지침

참고 : 점프 투 스프링부트 > SSL 

 

 

끝까지 읽어주셔서 감사합니다.