SY 개발일지
article thumbnail

현재 사이트에 들어가면 이런 식으로 주의를 요한다는 메세지가 뜹니다

이는 https가 적용되지 않아 암호화가 되지 않았으므로 주의해달라는 표시입니다. 따라서 이번 포스팅에서는 https를 적용하고 포트도 80, 443 포트로 변경해보도록 하겠습니다.

 

우선 let's encrypt를 진행하기 위해 nginx부터 설치해주도록 하겠습니다.

Nginx 설정

설치

설치 전 패키지 목록 업데이트

sudo apt-get update

 

nginx 설치

sudo apt-get install nginx

 

방화벽 설정

방화벽 설정

sudo ufw app list

다음과 같은 명령어를 입력하면 아래와 같은 리스트가 출력됩니다.

각 설정은 다음을 의미합니다.

  • Nginx HTTP: 포트 80번만 허용
  • Nginx HTTPS: 포트 443번만 허용
  • Nginx Full: 포트 80, 443번 허용

방화벽 설정을 적용하는 방법은 다음과 같습니다. 저는 Nginx Full로 설정해주도록 하겠습니다.

sudo ufw allow 'Nginx Full'

 

이후 아래 명령어를 통해 상태를 체크합니다.

sudo ufw status

 

만약 방화벽이 inactive 상태라면 아래 명령어를 입력하여 활성화합니다

sudo ufw enable

 

이러한 에러가 발생하면 ufw를 열어주어야 합니다.

Command may disrupt existing ssh connections. Proceed with operation (y|n)? n

 

먼저 설정을 해줍니다.

$ sudo ufw limit 22
Rules updated
Rules updated (v6)
$ sudo ufw allow 80
Rules updated
Rules updated (v6)
$ sudo ufw allow 443
Rules updated
Rules updated (v6)

 

그런 다음, 다시 실행하면 됩니다. 만약 위에 룰을 추가해주지 않으면 다시 접속하지 못할 수 있기 때문에 꼭 추가해주세요.

저는 추가해준 후 다음과 같은 상태가 확인되었습니다.

 

이제 우분투가 Nginx를 실행했는지 확인해보기 위해 다음 명령어를 입력해보겠습니다.

systemctl status nginx
● nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: enabled)
     Active: active (running) since Wed 2024-06-19 15:49:04 UTC; 20min ago
       Docs: man:nginx(8)
    Process: 516 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, stat>    Process: 535 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCC>   Main PID: 556 (nginx)
      Tasks: 2 (limit: 1130)
     Memory: 268.0K (peak: 3.2M swap: 1.4M swap peak: 1.4M)
        CPU: 16ms
     CGroup: /system.slice/nginx.service
             ├─556 "nginx: master process /usr/sbin/nginx -g daemon on; master_process on;"
             └─558 "nginx: worker process"

 

또한 웹 URL 에 제 IP를 입력하면 Nginx 페이지가 나타나게 됩니다.

Nginx 관련 명령어는 다음과 같습니다.

# 시작
sudo systemctl start nginx

# 종료
sudo systemctl stop nginx

# 재시작
sudo systemctl restart nginx

# 리로드 (변경된 설정을 적용하는 경우 사용. 기존 연결을 끊지 않음.)
sudo systemctl reload nginx

# 기본적으로 서버 시작 시 nginx가 자동으로 실행되는데, 이를 막고 싶은 경우
sudo systemctl disable nginx

# 서버 시작 시 자동으로 nginx를 실행하고 싶은 경우
sudo systemctl enable nginx

 

또한 초기 nginx 설정 파일은 다음과 같습니다.

cat /etc/nginx/nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;
error_log /var/log/nginx/error.log;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        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 TLSv1.3; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.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/*;
}


#mail {
#       # See sample authentication script at:
#       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#       # auth_http localhost/auth.php;
#       # pop3_capabilities "TOP" "USER";
#       # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#       server {
#               listen     localhost:110;
#               protocol   pop3;
#               proxy      on;
#       }
#
#       server {
#               listen     localhost:143;
#               protocol   imap;
#               proxy      on;
#       }
#}

 

여기에 다음 코드를 추가합니다. server_name만 각자 도메인으로 변경해주세요.

 http {
 	...
    include /etc/nginx/sites-enabled/*;
    
 	server {
                server_name restagram.shop;
                listen 80; # 80 번호로 오면
                location / {
                        proxy_set_header HOST $host;
                        proxy_pass http://127.0.0.1:3000; # 3000번으로 보냄 (reverse proxy)
                        proxy_redirect off;
                }
     }

 

Let's encrypt SSL 인증서 발급

저는 Let's encrypt를 이용해서 SSL 인증서를 발급받아보도록 하겠습니다.

다음 사이트에서 My HTTP website is running Nginx on Ubuntu20 을 입력한 것을 따라 하였습니다.

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

 

Certbot Instructions

Tagline

certbot.eff.org

 

먼저 snaped 를 설치해줍니다.

sudo apt update
sudo apt install snapd

 

만약 이전에 certbot을 설치한 적이 있다면 다음 명령어들로 삭제해주세요. 저는 이번이 처음이기 때문에 넘어가도록 하겠습니다.

# apt
sudo apt-get remove certbot

# dnf
sudo dnf remove certbot

# yum
sudo yum remove certbot

 

Certbot을 설치해줍니다.

sudo snap install --classic certbot
certbot 2.11.0 from Certbot Project (certbot-eff✓) installed

 

certbot 명령을 로컬에서 실행할 수 있도록 snap의 certbot 파일을 로컬의 cerbot과 링크(연결) 합니다.

-s 옵션은 심볼릭링크를 하겠다는 것을 의미합니다.

 

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

 

이제 Certbot을 이용해 nginx 설정을 해줍니다.

domain을 입력하라는 질문에서는 가비아 등에서 구매한 도메인을 입력해주면 됩니다.

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): [연락 받을 이메일을 입력합니다.]

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.4-April-3-2024.pdf. You must agree in
order to register with the ACME server. Do you agree?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: [약관에 동의하는지에 대한 문답입니다. Y를 입력해야 다음으로 진행됩니다.]

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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: [메일로 광고성 메일을 받을 것인지에 대한 문답입니다. N을 선택 시 처음 한번만 메일이 옵니다.]
Account registered.
Please enter the domain name(s) you would like on your certificate (comma and/or
space separated) (Enter 'c' to cancel): [등록할 도메인입니다. 저는 restagram.shop를 입력하였습니다.]
Requesting a certificate for restagram.shop

Successfully received certificate.
Certificate is saved at: /etc/letsencrypt/live/restagram.shop/fullchain.pem
Key is saved at:         /etc/letsencrypt/live/restagram.shop/privkey.pem
This certificate expires on 2024-09-18.
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
Successfully deployed certificate for restagram.shop to /etc/nginx/sites-enabled/default
Congratulations! You have successfully enabled HTTPS on https://restagram.shop

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

 

다음 출력에서 중요한 부분은 다음과 같습니다.

# https가 설정된 도메인
Requesting a certificate for restagram.shop 

# 공개키 경로
Certificate is saved at: /etc/letsencrypt/live/restagram.shop/fullchain.pem

# 비밀키 경로
Key is saved at:         /etc/letsencrypt/live/restagram.shop/privkey.pem 

# 만료 일자
This certificate expires on 2024-09-18.

 

여기까지 완료가 되었다면 certbot이 알아서 nginx 까지 설정을 해주었음을 확인할 수 있습니다. 제 nginx 파일은 다음과 같습니다.

user www-data;
worker_processes auto;
pid /run/nginx.pid;
error_log /var/log/nginx/error.log;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        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 TLSv1.3; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.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 {
    if ($host = restagram.shop) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


                server_name restagram.shop;
                listen 80;
                location / {
                        proxy_set_header HOST $host;
                        proxy_pass http://127.0.0.1:3000;
                        proxy_redirect off;
                }


}
}


#mail {
#       # See sample authentication script at:
#       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#       # auth_http localhost/auth.php;
#       # pop3_capabilities "TOP" "USER";
#       # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#       server {
#               listen     localhost:110;
#               protocol   pop3;
#               proxy      on;
#       }
#
#       server {
#               listen     localhost:143;
#               protocol   imap;
#               proxy      on;
#       }
#}

 

그런데 아무리봐도 제 설정 파일에는 다른 분들처럼 자동으로 443 설정이 없었습니다.

그래서 찾아보니 /etc/nginx/sites-enabled/default 파일에 nginx 설정이 되어 있었습니다.

해당 파일의 443 server 관련 reverse proxy 부분에 해당 코드만 추가해준 후 재시작해주었습니다

     location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                # try_files $uri $uri/ =404;

                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;
                proxy_pass http://127.0.0.1:3000;
                proxy_redirect off;

        }

 

 

 

이제 설정을 변경하였으니 nginx를 재시작 하겠습니다.

 sudo systemctl restart nginx

 

 

이렇게 모든 배포가 완료되었습니다.

아직 CORS 등 여러 수정사항이 있지만 도커와 젠킨스, 그리고 Github webhook을 이용한 자동 배포 로직은 완성되었습니다🥰

 

 

참고

 

Ubuntu 20.04에서 Nginx 설치 및 설정하기

이 포스트는 프로젝트를 배포하는 과정에서 참고한 여러 개의 포스트를 종합한 글입니다. Ubuntu 20.04에 Nginx 설치하기 Nginx 설치 방화벽 설정 위 명령을 실행하면 아래와 같은 리스트가 출력됩니

jaehyeon48.github.io

 

 

안복잡한 방화벽 ufw 설치하기 - Firefish를 설치해보자 (비전문가 대상)

구매한 도메인과 빌린 컴퓨터의 IP 주소를 연결해주기 전에, 방화벽을 먼저 설치해줍시다. 방화벽: 지정된 통로로만 다니렴 빌린 컴퓨터의 보안 수준을 높기기 위해 방화벽을 설치해줄 겁니다.

opentutorials.org

 

Certbot Instructions

Tagline

certbot.eff.org

 

Nginx를 이용하여 https 적용하는 법

Nginx를 이용하여 https 적용하는 법. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

 

profile

SY 개발일지

@SY 키키

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!