[Study] 개발 공부
AWS EC2 배포 해보기
지공A
2024. 6. 7. 16:40
엘리스 프로젝트 진행 시 배포했던 방식으로 셀프 배포 해보기!
엔진엑스 설정에서 너무 많이 고생해서 기록용으로 남긴다.
백엔드 cors 설정과 프론트엔드 api url을 바꾸는 것은 잊지 말자
참고) 팀 노션 페이지, 엔진엑스 설정은 코치님 메시지 참고
1. EC2 인스턴스 생성
- 리전은 서울로
- Ubuntu 서버 선택
- 인스턴스 유형은 프리티어 사용 가능한 것으로 선택
- 네트워크 설정 HTTP/HTTPS 트래픽 허용
- 키 페어를 생성해서 저장
- 다운로드 한 키 페어를 프로젝트 루트에 넣고, gitignore에 추가
2. 인스턴스 연결
#터미널에서 .pem 파일이 존재하는 디렉토리로 이동
cd [디렉토리]
cd [디렉토리]
#서버 접속 명령어
#위에 첨부된 사진) 생성된 인스턴스마다 AWS EC2가 명령어 자동생성해준 것 복붙
ssh -i "test.pem" ubuntu@ec2-44-201-114-166.compute-1.amazonaws.com
3. 서버 환경설정
# 1. 원격 저장소에서 clone 받기 (elice gitlab은 SSH 인증키 필요해서 HTTP로 연결)
git clone (본인 레포 주소 입력)
# 2. npm 설치 후
sudo apt-get update
sudo apt install npm
# 2-2. package.json 의존성 설치
cd [디렉토리]
npm install
# 3. nvm 패키지 설치 후 터미널 재실행 명령어 입력
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
source ~/.bashrc
# 4. pm2 설치
sudo npm i -g pm2
# 5. nginx 설치
sudo apt update
sudo apt install nginx
sudo nginx -t
# 6. .env 파일 생성, vim입력(PORT 번호 필수), 내용 확인
touch .env
vim .env
cat .env
4. 엔진엑스 설정
- 포트 번호는 설정한 포트 번호에 따라 설정해준다.
# 설정 파일 수정
sudo nano /etc/nginx/sites-available/default
server {
listen 80 default_server;
listen [::]:80 default_server;
# SSL configuration
#
# listen 443 ssl default_server;
# listen [::]:443 ssl default_server;
#
# Note: You should disable gzip for SSL traffic.
# See: https://bugs.debian.org/773332
#
# Read up on ssl_ciphers to ensure a secure configuration.
# See: https://bugs.debian.org/765782
#
# Self signed certs generated by the ssl-cert package
# Don't use them in a production server!
#
# include snippets/snakeoil.conf;
root /var/www/html;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
proxy_pass http://127.0.0.1:3000;
}
location /api {
proxy_pass http://127.0.0.1:8080/api;
}
location /test-api {
proxy_pass http://127.0.0.1:8081/api;
}
# pass PHP scripts to FastCGI server
#
#location ~ \.php$ {
# include snippets/fastcgi-php.conf;
#
# # With php-fpm (or other unix sockets):
# fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
# # With php-cgi (or other tcp sockets):
# fastcgi_pass 127.0.0.1:9000;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
5. 저장 후 nginx 재실행
# 문법 오류 없음을 테스트
sudo nginx -t
# nginx 재실행 (재실행해야, 수정된 설정파일이 반영됨)
sudo systemctl reload nginx
# (참고) 만약 위 명령어가 안 되는 경우
sudo service nginx restart
6. 백엔드와 프론트엔드 프로젝트 pm2 시작/재시작
- 테스트는 테스트 서버 설정 유무에 따라
- 명령어는 프로젝트 별로 다를 수 있
# 백엔드 test 시작
PORT=8081 pm2 start bin/index.js --name backend-test
# 재시작
pm2 restart backend-test
# 백엔드 배포 시작
NODE_ENV=production pm2 start bin/index.js --name backend-prod
# 재시작
pm2 restart backend-prod
# 프론트엔드 시작
pm2 start src/app.js --name frontend
# 재시작
pm2 restart frontend