
EC2 nginx 에 react 서버를 배포 하며 생긴 오류를 정리한 글입니다.
먼저 docker volume을 쉽게 세팅하기 위해 docker compose 로 nginx 컨테이너를 정의 하였습니다.
version: '3'
services:
nginx:
container_name: web
image: nginx:alpine
ports:
- "80:80"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
- ./static:/static
항상 docker image는 alpine (작은 용량) 을 지향하고 있습니다.
또한 EC2안 docker-compose와 같은 레벨에 있는 static 폴더와 nginx 컨테이너 안 /static 폴더를 마운트 하여 nginx 컨테이너를 종료하지 않고 쉽게 React 정적 파일을 배포하게 되었습니다.
nginx.conf 파일을 컨테이너 안 conf 파일에 마운트하여 본인이 설정한 nginx.conf 를 쉽게 적용할수 있게 하였습니다.
nginx를 프록시 서버의 역할로 배포할때는 다르겠지만 나는 순순히 정적파일을 배포하기 위해 nginx 를 선택했다.
따라서 간단하게 정적 파일만 제공하는 conf 로 설정하였다.
또한 try_files $uri $uri/ /index.html; 구문을 넣어주어 react-route-dom을 사용할때 refresh 해도 index.html 에서 정적 데이터를 가져올수 있게 설정하였다.
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log error;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
server {
listen 80;
root /static ;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
include /etc/nginx/mime.types;
}
}
index.html 에
<base href="/" /> 를 추가 하여
Unexpected token '<' (at main.f27b23cf.js:1:1) 에러를 해결하자
# (보통 다른 페이지에서 refresh 할때 일어남)
try_files $uri $uri/ /index.html; 를 넣는다고 다 해결되는게 아니더라
다양한 방법이 있겠지만 본인은 Github Action의 runner에서 react를 빌드하고 scp 로 직접 파일을 전송해 주었다.
name: Deploy
on:
push:
branches:
- main
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup .env
run: |
echo "${{ secrets.DOT_ENV }}" > .env
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- name: Build
run: npm run build
- name: Deploy to EC2
uses: appleboy/scp-action@master
with:
host: ${{ secrets.EC2_HOST }}
username: ${{ secrets.EC2_USERNAME }}
key: ${{ secrets.EC2_KEY }}
# build 안 모든 파일을 EC2로 전송
source: build/*
target: /home/ubuntu/static/
strip_components: 1
npm install 이 아닌 npm ci 를 한다.자동화 환경에서는 npm ci 로 개발 의존성을 제거 해 주자
ci 로 안하면 에러가 마구 뜬다…
@testing-library/jest-dom 의 의존성을 없애 주자.npm ci 로 했을때 개발 의존성인 jest 를 없애야 build 가능하다.
Eslint 에 걸리면 실패한다…package.json에서 명령을바꿔주자
"scripts": {
...
"build": "CI=false && react-scripts build",
...
}
Eslint 에 걸리는 코드를 모두 수정하면 되긴 한다. (하지만 귀찮 ㅋ)
ENV *NODE_OPTIONS*=--max-old-space-size=4096
위 옵션을 주어 노드의 메모리를 증가 시켜 준다… (default가 512MB or 1GB 이지만 버전마다 다르다고 한다.)