certbot https 인증서 재발급하기

Maliethy·2021년 4월 23일
0

nodejs

목록 보기
1/1

aws에 배포한 ymillonga project에서 예상치 못한 aws이용료가 만원정도 나온 뒤로 ec2는 정지상태로 두고 , 탄력적 ip, route53는 모두 삭제했다.
3/9에 https인증서 발급을 했던 Let's Encrypt에서 Let's Encrypt certificate expiration notice for domain "ymillonga.xyz"라는 이메일을 받았다.
3개월이 채 안되는 시간 회사를 다니는 동안 잊고 있었던 ymillonga프로젝트를 오늘에서야 살리려니 까막득하기만 했다. 차근차근 처음 배포를 어떻게 했는지 zerocho님의 react nodebird강의를 돌려보고 전에 aws배포를 위해 메모해 두었던 내용들을 다시 읽으며 기억을 되살려보았다.

먼저 한 일은 ec2인스턴스를 활성화시킨 후 탄력적 ip를 만들고 이를 front와 back 두 인스턴스와 연결시키는 것이었다.
탄력적 ip로 주소를 고정한 뒤에는 route53에 a유형으로 ymillonga.xyz, api.ymillonga.xyz를 등록하고 호스팅케이알에서 도메인 네임서버를 다음의 새로 생성한 호스팅영역 주소로 바꾼 것이다.

ns-1139.awsdns-14.org
ns-245.awsdns-30.com
ns-901.awsdns-48.net
ns-1730.awsdns-24.co.uk

aws를 원상복귀한 뒤에는 ubuntu서버로 들어가 back과 front 각각에서 cerbot으로 새로운 인증서를 발급받기를 시도했다.

  1. sudo certbot --nginx

back 서버에서 2번이 아닌 1번을 선택했을 때 다음의 에러가 발생해서 당황했다. 다시 2번 api.ymillonga.xyz를 선택하니 정상적으로 인증서가 발급되었다.

which names would you like to activate HTTPS for?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: ymillonga.xyz
2: api.ymillonga.xyz
3: www.ymillonga.xyz
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate numbers separated by commas and/or spaces, or leave input
blank to select all options shown (Enter 'c' to cancel): 1
Requesting a certificate for ymillonga.xyz
Performing the following challenges:
http-01 challenge for ymillonga.xyz
Waiting for verification...
Challenge failed for domain ymillonga.xyz
http-01 challenge for ymillonga.xyz
Cleaning up challenges
Some challenges have failed.

IMPORTANT NOTES:
 - The following errors were reported by the server:

   Domain: ymillonga.xyz
   Type:   unauthorized
   Detail: Invalid response from
   https://ymillonga.xyz/.well-known/acme-challenge/j9uQSO0KTGRXKxwBN5G2GehSLXFS0o7c5qO3-xMmNAI
   [13.209.253.22]: "<html>\r\n<head><title>502 Bad
   Gateway</title></head>\r\n<body
   bgcolor=\"white\">\r\n<center><h1>502 Bad
   Gateway</h1></center>\r\n<hr><cen"

   To fix these errors, please make sure that your domain name was       
   entered correctly and the DNS A/AAAA record(s) for that domain        
   contain(s) the right IP address.

인증서 재발급 원할 시 certbot renew라는 명령어를 ubuntu에서 실행하면 간단하게 재발급이 되는 걸 알고 나니 참 허탈했다. 회사 다닐 때는 그걸 몰라 속으로만 끙끙 앓고 갱신 기간을 훌쩍 넘겨버렸던 것이다.

  1. 인증서 발급 후 vim /etc/nginx/nginx.conf로 nginx설정에 들어가보았다. 다음과 같이 cerbot이 자동으로 reverse-proxy를 위한 설정을 생성해주었다.
    nginx엔진는 https, cashing, 정적파일 제공 등을 담당하고,
    next는 노드, 데이터베이스 로직을 담당한다.
    reverse-proxy로 front서버의 경우 nginx서버가 80번으로 온 요청은 next(3050)서버에 https(443번)으로 redirect해서 보내준다. 애초에 https 전용 포트인 443으로 요청이 오면 ssl_certificate과 ssl_certificate_key 값만 잘 설정해주면 된다. zerocho님의 블로그와 강의를 참고해가며 기억을 되살려 nginx가 어떤 일을 하는지 이해하며 해당 환경설정 코드를 해독해보았다.

간단하게 다시 정리해보면 아래의 환경설정은
https는 포트443로 바로 next(3060)로 보내고
80은 리버스프록시해서 next 서버로 보낸다

는 내용이다.

http {
        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

 ##
        # Gzip Settings
        ##

        gzip on;

        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;

  server {
                server_name ymillonga.xyz www.ymillonga.xyz;
                return 301 https://ymillonga.xyz$request_uri;
        }
        server {
                server_name api.ymillonga.xyz;
                return 301 https://$host$request_uri;
        }
        server {
                listen 443 ssl;
                server_name ymillonga.xyz;
                ssl_certificate /etc/letsencrypt/live/api.ymillonga.xyz/fullchain.pem; # managed by Certbot       
                ssl_certificate_key /etc/letsencrypt/live/api.ymillonga.xyz/privkey.pem; # managed by Certbot     
                include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
                ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
                location / {
                        proxy_set_header Host $host;
                        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                        proxy_set_header X-Forwarded-Proto $scheme;
                        proxy_set_header Upgrade $http_upgrade;
                        proxy_set_header Connection "upgrade";
                        proxy_set_header X-Real-IP $remote_addr;
 proxy_pass http://127.0.0.1:3050;
                        proxy_redirect off;
               }
       }
       server {
                listen 443 ssl;
                server_name api.ymillonga.xyz;
                ssl_certificate /etc/letsencrypt/live/api.ymillonga.xyz/fullchain.pem; # managed by Certbot       
                ssl_certificate_key /etc/letsencrypt/live/api.ymillonga.xyz/privkey.pem; # managed by Certbot     
               include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
                ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
                location / {
                        proxy_set_header Host $host;
                        proxy_set_header X-Forwarded-Proto $scheme;
                        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                        proxy_set_header X-Real-IP $remote_addr;
                        proxy_set_header Upgrade $http_upgrade;
                        proxy_set_header Connection "upgrade";
                        proxy_pass http://127.0.0.1:3051;
                        proxy_redirect off;
                }
        }
}

    include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;

      server {
    if ($host = ymillonga.xyz) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

                server_name ymillonga.xyz;
                location / {
            proxy_set_header HOST $host;
           proxy_pass http://127.0.0.1:3050;
          proxy_redirect off;
                 }
}
server {
                server_name ymillonga.xyz www.ymillonga.xyz;
                return 301 https://ymillonga.xyz$request_uri;
        }

server {
                server_name api.ymillonga.xyz;
                return 301 https://$host$request_uri;
        }
        server {
                listen 443 ssl;
                server_name ymillonga.xyz;
    ssl_certificate /etc/letsencrypt/live/ymillonga.xyz/fullchain.pem;   
            # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/ymillonga.xyz/privkey.pem; 
            # managed by Certbot
                include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
                ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
                location / {
                        proxy_set_header Host $host;
                        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                        proxy_set_header X-Forwarded-Proto $scheme;      
                        proxy_set_header Upgrade $http_upgrade;
                        proxy_set_header Connection "upgrade";
                        proxy_set_header X-Real-IP $remote_addr;
                        proxy_pass http://127.0.0.1:3050;
                        proxy_redirect off;
               }
}
server {
                listen 443 ssl;
                server_name api.ymillonga.xyz;
                ssl_certificate /etc/letsencrypt/live/ymillonga.xyz/fullchain.pem;
            # managed by Certbot
                ssl_certificate_key /etc/letsencrypt/live/ymillonga.xyz/privkey.pem;
            # managed by Certbot
               include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
                ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
                location / {
                        proxy_set_header Host $host;
                        proxy_set_header X-Forwarded-Proto $scheme;      
                        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                        proxy_set_header X-Real-IP $remote_addr;
                        proxy_set_header Upgrade $http_upgrade;
                        proxy_set_header Connection "upgrade";
                        proxy_pass http://127.0.0.1:3051;
                        proxy_redirect off;
                }
        }
}
  1. 위의 환경설정 파일에 include /etc/nginx/sites-enabled/;
    라는 명령어가 있을 때는 sites-enabled파일를 include한 경우로 그 파일에서 따로 설정을 해야한다고 zerocho님 블로그에 나와있어서 vim /etc/nginx/sites-enabled/
    로 들어가보았으나 내가 따로 수정한 것은 없었다.

4.certbot 자동갱신을 위해 sudo vim /etc/cron.d/certbot로 들어갔더니 다음의 명령어도 이미 적혀 있었다. SHELL에서 S가 빠져있어서 파일 내용을 고치려는데 esc > wq!를 열심히 쳤으나 read only file이라는 오류가 계속 나와 당황했다.. permission denied 문제이므로 꼭 sudo를 붙여야 한다.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
0 /12 * * root certbot -q renew --nginx --renew-hook 'service nginx reload'

  1. 모든 작업이 완료된 것 같아 ymillonga.xyz로 들어갔더니 502 Bad Gateway가 떴다.
nginx 502 Bad Gateway발생 
ubuntu@ip-172-31-39-192:~$ tail /var/log/nginx/error.log
2021/04/23 09:16:36 [warn] 2140#2140: conflicting server name "ymillonga.xyz" on 0.0.0.0:80, ignored
2021/04/23 09:16:36 [warn] 2140#2140: conflicting server name "ymillonga.xyz" on 0.0.0.0:80, ignored
2021/04/23 09:16:36 [warn] 2152#2152: conflicting server name "ymillonga.xyz" on 0.0.0.0:80, ignored
2021/04/23 09:16:36 [warn] 2152#2152: conflicting server name "ymillonga.xyz" on 0.0.0.0:80, ignored
2021/04/23 09:16:42 [error] 2160#2160: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 211.179.15.109, server: ymillonga.xyz, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:3050/", host: "ymillonga.xyz"
2021/04/23 09:16:42 [error] 2160#2160: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 211.179.15.109, server: ymillonga.xyz, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:3050/favicon.ico", host: "ymillonga.xyz", referrer: "https://ymillonga.xyz/"
2021/04/23 09:16:44 [error] 2160#2160: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 211.179.15.109, server: ymillonga.xyz, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:3050/", host: "ymillonga.xyz"
2021/04/23 09:16:44 [error] 2160#2160: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 211.179.15.109, server: ymillonga.xyz, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:3050/favicon.ico", host: "ymillonga.xyz", referrer: "https://ymillonga.xyz/"
2021/04/23 09:16:57 [error] 2160#2160: *8 connect() failed (111: Connection refused) while connecting to upstream, client: 211.179.15.109, server: ymillonga.xyz, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:3050/", host: "ymillonga.xyz"
2021/04/23 09:16:59 [error] 2160#2160: *8 connect() failed (111: Connection refused) while connecting to upstream, client: 211.179.15.109, server: ymillonga.xyz, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:3050/favicon.ico", host: "ymillonga.xyz", referrer: "https://ymillonga.xyz/"

[error] 2160#2160: *1 connect() failed (111: Connection refused) while connecting to upstream 로 검색해보니 나와 비슷한 에러가 발생한 분이 적으신 다음의 문구에서 혹시 back의 node서버와 front next서버가 꺼져있는 것이 아닌가 의구심이 들었다.

MDN의 설명에 따르면 게이트웨이 혹은 프록시로서 동작하는 서버가 더 뒷단의 upstream 서버로부터 유효하지 않은 응답을 받은 경우 이러한 에러가 나올 수 있다.

ubuntu에서 git 폴더의 back과 front 하위폴더로 들어가
front는
sudo npx pm2 start npm -- start && sudo npx pm2 monit

back은
sudo npm start && sudo npx pm2 monit

명령어로 두 서버를 살려내니 드디어 ymillonga.xyz가 다시 살아났다!

회사다닌 동안 고쳐야지 하면서 뒤로 밀어두었던 일을 생각보다 빠르게 해결해내서 회사를 피치 못하게 그만 두고 우울한 와중에도 참 기쁘고 뿌듯했다.

profile
바꿀 수 있는 것에 주목하자

0개의 댓글