보통은 아래와 같은 방식으로 앱을 실행

$ npm run start:local
$ npm run start:prod

 

여기에 맞춰서 

app.js 와 pakage.json 을 수정

 

app.js 상단에 코드 추가

dotenv.config({ path: `.env.${process.env.NODE_ENV}` });
console.log(`Start ${process.env.NODE_ENV} mode`);
console.log(process.env);

 

package.json 에 실행 스크립트 추가

"scripts": {
         "start:local": "NODE_ENV=local node app.js",
         "start:prod": "NODE_ENV=prod node app.js",
         "test": "echo \"Error: no test specified\" && exit 1"
},

실행하고 싶은 모드에 따라 다른 .env 파일을 반영

 

일단 실행하는 방법은 app.js 를 실행 시킬때 argument 를 제공하는 방식을 선택

$ node app.js local

$ node app.js product

 

그 후 주어진 argument에 따라 어떻게 .env 파일을 구성할 것인가에 대해서는 

아래 두가지를 생각해보았다.

1. 변수들을 다른 파일에 기록하여 호출하기

설정해둔 값을 실행하고자는 환경에 따라 다르게 반영이 가능하다고 생각하여

 

const dotenv = require('dotenv');
const env = process.argv[2] || 'local';
dotenv.config({ path: `.env.${env}` });
console.log(`Start ${process.env.APP_ENV} mode`);

 

2. 하나의 파일에 기록하고 변수들의 앞부분에 구분되는 문자를 넣기

LOCAL_DB_HOST='local'
PRODUCT_DB_HOST='address'

 

그 후 아래와 같이 호출하여 사용.

const dotenv = require('dotenv');
const env = process.argv[2]||'local'
const dbHost = process.env[`${env.toUpperCase()}_DB_HOST`];
const dbUser = process.env[`${env.toUpperCase()}_DB_USER`];

 

 

결론은 1번을 선택

아무래도 따로 파일을 관리해야 정보를 구별하기도 쉽고, 

현재 내가 작성해둔 코드에서 다른 .env 파일을 이용하여 호출할 때  app.js 에서만 조정을 해주면 된다..ㅎㅎ

참고 사이트

 https://certbot.eff.org/instructions

 

Installing snap on Ubuntu

snapd 설치

$ sudo apt update
$ sudo apt install snapd

 

snapd 설치 후 확인

$ sudo snap install hello-world
hello-world 6.4 from Canonical✓ installed
$ hello-world
Hello World!

 

cerbot 이 설치되어 있다면 아래 명령어 중 하나를 이용하여 삭제

$ sudo apt-get remove certbot
$ sudo dnf remove certbot
$ sudo yum remove certbot

 

cerbot 설치

$ sudo snap install --classic certbot

 

cerbot 커맨드 설정

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

 

cerbot 이용해서  certification을 얻고 설치하기

sudo certbot --nginx -d 도메인주소

 

renewal 확인

$ sudo certbot renew --dry-run

참고 사이트

https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-22-04#step-5-%E2%80%93-setting-up-server-blocks-

Installing nginx on Ubuntu 22.04

nginx 설치

$ sudo apt update
$ sudo apt install nginx

 

방화벽(firewall) 설정 

$ sudo ufw app list

Available applications:
  Nginx Full
  Nginx HTTP
  Nginx HTTPS
  OpenSSH
  • 위에 출력된 모든 옵션이 설치 되어 있어야 한다.
    • Nginx HTTP:  80번 포트 만 허용 (normal, unencrypted web traffic)
    • Nginx HTTPS:  443번 포트만 허용 (TLS/SSL encrypted traffic)
    • Nginx Full:  80번 과 443번 포트 둘다 허용
  • 80번 포트 허용 방법
$ sudo ufw allow 'Nginx HTTP'
  • 현재 상태 확인 ( 허용한 application 이 나열된다)
$ sudo ufw status

Status: active

To                         Action      From
--                         ------      ----
Nginx HTTP                 ALLOW       Anywhere
OpenSSH                    ALLOW       Anywhere
Nginx HTTPS                ALLOW       Anywhere
Nginx HTTP (v6)            ALLOW       Anywhere (v6)
OpenSSH (v6)               ALLOW       Anywhere (v6)
Nginx HTTPS (v6)           ALLOW       Anywhere (v6)

 

  •  응답이 inactive 이면 아래 명령어로 활성화 시키기
$ sudo ufw enable

 

서버가 작동하고 있는 가 확인

$ systemctl status nginx

 

할당 받은 공인 아이피(public ip) 를 확인 

$ curl -4 icanhazip.com
$ curl ifconfig.me

- 둘 중 하나를 입력하면 할당받은 ip 가 출력된다.

- 출력된 ip를 크롬이나 다른 인터넷 브라우져에 입력하면 아래와 같은 문구가 나오면 설치완료

         "Welcome to nginx!"

 

EC2 에서 서버를 3000번 포트를 이용해서 배포를 했을때 방화벽때문에 접속이 안될 수도 있다.

이럴때는 3000번 포트도 허용해주기

$ sudo ufw allow 3000

 

서버블록 설정

도메인을 위한 폴더 생성

$ sudo mkdir -p /var/www/your_domain/html

 

해당 폴더의 소유자 설정

$ sudo chown -R $USER:$USER /var/www/your_domain/html

 

권한설정

$ sudo chmod -R 755 /var/www/your_domain

 

index.html 생성

$ sudo vi /var/www/도메인 이름/html/index.html

 

- 아래 내용 입력 후  esc -> :wq  로 저장후 닫기

<html>
    <head>
        <title>Welcome to your_domain!</title>
    </head>
    <body>
        <h1>Success!  The your_domain server block is working!</h1>
    </body>
</html>

 

서버블록 생성

$ sudo vi /etc/nginx/sites-available/your_domain

 

-  아래 내용을 입력

server {
        listen 80;
        listen [::]:80;

        root /var/www/your_domain/html;
        index index.html index.htm index.nginx-debian.html;

        server_name your_domain www.your_domain;

        location / {
                try_files $uri $uri/ =404;
        }
}

 

링크 생성

$ sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/

 

nginx.conf 설정 

- 서버 이름을 추가할 때 발생할 수 있는 해시 버킷 메모리 문제 (hash bucket memory problem) 를 방지하기 위함

sudo nano /etc/nginx/nginx.conf
  •  #server_names_hash_bucket_size 64; 을 찾아서 앞에 있는 # 을 삭제한 후 저장

설정한 내용에 문제 없는지 확인

$ sudo nginx -t

 

문제가 없으면 nginx 재시작

$ sudo systemctl restart nginx

 

이제 부여 받은 도메인을 인터넷 창에 입력하면 index.html 에 입력한 문구가 출력된다. 

ngnix 명령어

  • ngnix 중지
$ sudo systemctl stop nginx
  • nginx 시작
$ sudo systemctl start nginx
  • nginx 재시작
$ sudo systemctl restart nginx

 

 

+ Recent posts