그저 내가 되었고

항해99) 7주차:: ⚡️백엔드 서버 배포(Ubuntu & Nginx) 본문

개발/항해99 9기

항해99) 7주차:: ⚡️백엔드 서버 배포(Ubuntu & Nginx)

hyuunii 2022. 11. 1. 01:14

Ubuntu

클론 받고 나서... 제발~~!~!! npm i 해주기!!! 


Nginx

Web Server 의 구축을 도와주는 소프트웨어. 웹 서버 소프트웨어 라고도 불리며, 웹 어플리케이션을 안정적으로 제공할 수 있도록 도와주는 역할을 함. 동시 접속에 특화된 서버.

웹 서버 소프트웨어 에는 NginX 와도 많이 비교되며 널리 알려진Apache 도 있다. 

Nginx 서버를 앞단에 두어 Express가 사용하는 실제 포트를 숨기고, Nginx의 80번 포트를 통해 Reverse proxing(사용자가 실제 서버의 정보를 알지 못하게 함을 의미. 사용자들이 서버에 요청한 내용을 리버스 프록시가 배후의 서버에서 응답 데이터를 받아와 다시 사용자에게 전송)함으로써 보안 이슈를 방지하고 Nginx의 여러 기능도 사용할 수 있다.

 

1. 설치

$ sudo apt-get update
$ sudo apt-get install nginx

 

2. 설치 체크

설치 후 브라우저에서 서버 아이피 주소 접속해서 Welcome to nginx! 뜨면 일단 설치 성공

 

3. 프록시 설정

$ cd /etc/nginx/sites-available/
$ vi [example]

/etc/nginx/sites-available/ 디렉토리로 이동한 뒤 아무 이름으로 편집기를 생성한다. (default 파일은 남겨두어도 됨.)

 

server {
        server_name kyuudukk.shop www.kyuudukk.shop;
        location / {
                proxy_pass http://127.0.0.1:3000;
        }
}

위와 같이 작성한다. 해당 코드의 의미는 80번 포트로의 요청은 로컬의 3000번 포트로 요청을 처리한다는 의미이다.

server_name에는 구매한 도메인을 작성하면 된다.

 

$ sudo ln -s /etc/nginx/sites-available/[example] /etc/nginx/sites-enabled/

site-enabled 디렉토리에 [example] 파일을 링크(ln)를 통해 생성 및 연결한다.

 

$ sudo service nginx restart

마지막으로 nginx를 재시작 해준다.

 

 

Nginx로 https 적용하기

1. certbot 설치하기

# snap을 이용하여 core 설치 -> snap을 최신 버전으로 유지하기 위해 설치
$ sudo snap install core

# core를 refresh 해준다.
$ sudo snap refresh core

# 기존에 잘못된 certbot이 설치되어있을 수도 있으니 삭제 해준다.
$ sudo apt remove certbot

# certbot 설치
$ sudo snap install --classic certbot

# certbot 명령을 로컬에서 실행할 수 있도록 snap의 certbot 파일을 로컬의 cerbot과 링크(연결) 시켜준다. -s 옵션은 심볼릭링크를 하겠다는 것.
$ ln -s /snap/bin/certbot /usr/bin/certbot

 

2. certbot으로 ssl 인증서 받아오기: certbot을 이용해 ssl 인증서를 받아온 뒤 cerbot이 스스로 nginx설정을 해주도록한다. 아래 명령을 수행하면 여러 질문이 등장한다. 질문에 맞춰 답을 해주면 된다. domain을 입력하라는 질문에서는 본인이 사용할 Domain을 입력해주면 된다.

$ sudo certbot --nginx

성공?

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Your existing certificate has been successfully renewed, and the new certificate
has been installed.

The new certificate covers the following domains: https://kyuudukk.shop/ # https가 설정된 도메인
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Subscribe to the EFF mailing list (email: okyee8335@naver.com).

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/kyuudukk.shop/fullchain.pem # 공개키 경로이므로 기억
   Your key file has been saved at:
   /etc/letsencrypt/live/kyuudukk.shop/privkey.pem # 비밀키 경로이므로 기억
   Your certificate will expire on 2021-08-15. To obtain a new or
   tweaked version of this certificate in the future, simply run
   certbot again with the "certonly" option. To non-interactively
   renew *all* of your certificates, run "certbot renew"
 - 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

 

여기까지 설정을 마쳤다면, certbot이 알아서 Nginx 설정까지 해줬기 때문에 https 설정도 되어있을 것. 아래와 같이 설정됨.

# 443 포트로 접근시 ssl을 적용한 뒤 3000포트로 요청을 전달해주도록 하는 설정.
server {
        server_name idu-market.shop;

        location / {
                proxy_pass http://127.0.0.1:3000;
        }

        listen 443 ssl; # managed by Certbot
        ssl_certificate /etc/letsencrypt/live/idu-market.shop/fullchain.pem; # managed by Cert>
        ssl_certificate_key /etc/letsencrypt/live/idu-market.shop/privkey.pem; # managed by Ce>

        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

# 80 포트로 접근시 443 포트로 리다이렉트 시켜주는 설정
server {
        if ($host = idu-market.shop) {
                return 301 https://$host$request_uri;
        } # managed by Certbot


        listen 80;
        server_name idu-market.shop;
        return 404; # managed by Certbot
}

 

 

 

 

+ certbot을 이용하여 ssl인증서를 발급할 경우 3개월마다 갱신을 해줘야 한다. -> 무료이기 때문에 안전하게 서비스를 이용하려면 갱신해야함. 아래 명령을 통해 갱신해줄 수 있다.

$ certbot renew

 

or 자동갱신 설정도 가능하다.

crontab -e
0 1 * * * /usr/bin/certbot renew --quiet

(매일 오전 1시에 서트봇 갱신을 요청 &  --quiet 옵션은 서트봇 실행 결과로 표시하는 메시지를 표시하지 않는 옵션.)

 

 

갱신 커맨드가 잘 실행되는지 확인

/usr/bin/certbot renew

 

방금 인증서를 만든 상태이므로 갱신할 이유가 없고, 그러므로 아래와 같이 나오면 다 잘 된 것.

Certificate not yet due for renewal