Amazon EC2 인스턴스에서 React, Express, 및 Nginx를 설정하려면 다음 단계를 따르세요.
먼저 EC2 인스턴스에 접속하여 Node.js와 npm을 설치합니다.
curl -o- [https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh](https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh) | bash source ~/.bashrc nvm install node
React 프로젝트를 생성합니다.
npm install -g create-react-app create-react-app 프로젝트
프로젝트 디렉리에서 Express 백엔드를 추가합니다.
npm install express --save
백엔드 서버 코드를 작성하기 위해 프로젝트 루트 디렉토리에
server.js
파일 만듭니다.
혹은 리액트 루트 디렉토리 안에 server 폴더안에server.js
를 만들어도 됩니다.
코드 구성은 다음과 같아야 합니다.const express = require('express'); const app = express(); const port = process.env.PORT || 8000; app.get('/api', (req, res) => { res.json({ message: 'Hello from the server!' }); }); app.listen(port, () => { console.log(`Server running on port ${port}`); });
React 프로젝트를 빌드합니다.
npm run build
빌드가 완료되면,
build
디렉토리가 생성됩니다.리눅스에 Nginx를 설치합니다.
Ubuntu 사용 시:sudo apt-get update sudo apt-get install nginx
Amazon Linux 사용 시:
sudo amazon-linux-extras install nginx1.12
Nginx 설정을 수정합니다.
다음과 같이/etc/nginx/sites-available/default
(Ubuntu의 경우) 또는/etc/nginx/conf/default.conf
(Amazon Linux의 경우)를 수정하십시오.server { listen 80; server\_name your\_domain\_name; location / { root /path/to/your/frontend/build; index index.html; try\_files $uri $uri/ /index.html; } location /api { proxy\_pass http://localhost:8000; proxy\_http\_version 1.1; proxy\_set\_header Upgrade $http\_upgrade; proxy\_set\_header Connection 'upgrade'; proxy\_set\_header Host $host; proxy\_cache\_bypass $http\_upgrade; } }
Nginx 서버를 다시 시작합니다.
sudo service nginx restart
또는
sudo systemctl restart nginx
Express 백엔드 서버를 실행합니다
node server.js
끝났습니다! 이제 React 프론트엔드가 Nginx를 통해 제공되고 Express 백엔드 서버가 8000 포트에서 실행됩니다.
프론트엔드에서 백엔드 API 호출시/api
엔드포인트를 사용하면 됩니다.
'AWS' 카테고리의 다른 글
VSCODE로 EC2 SSH 접속하는 방법 (0) | 2022.11.02 |
---|