0. 들어가며
- React와 FastAPI는 각각 frontend와 backend에서 사람들이 많이 사용하는 라이브러리다.
- 이 글은 React frontend와 FastAPI backend를 사용한 web application 개발 환경을 구축하는 방법을 다룬다.
- 이 글의 방법을 적용하기 위해서는 사전에 node와 docker를 설치해야 한다.
1. 디렉토리 생성
1.1. 메인 디렉토리 생성
mkdir my-web
cd my-web
- 코드를 담을 디렉토리를 생성한 뒤 생성한 디렉토리로 이동합니다.
- my-web은 이 글에서 사용한 이름이며 변경 가능하다.
1.2. (Optional) Assets 디렉토리 생성
mkdir assets
- 이미지와 같은 자원을 관리하기 위한 디렉토리를 만든다.
2. Frontend 설정
2.1. Create React App
npx create-react-app frontend
rm -rf frontend/.git
- create-react-app으로 frontend 디렉토리를 생성한다.
- 메인 디렉토리에서 버전 관리를 할 것이기 때문에 frontend의 git 디렉토리는 삭제한다.
2.2. Frontend Dockerfile
vim frontend/Dockerfile
- Frontend Dockerfile 작성을 위해 에디터를 켠다.
- VS Code와 같은 에디터를 사용해도 된다.
# frontend/Dockerfile
FROM node
WORKDIR /workspace
RUN npm install axios
CMD ["npm", "start"]
- Dockerfile의 내용을 복사하여 붙여넣는다.
- RUN npm install axios: axios 패키지를 설치하는 명령어. 다른 필요한 패키지를 추가하거나 필요 없는 경우 제거하면 된다.
3. Backend 설정
3.1. Backend Dockerfile
mkdir backend
vim backend/Dockerfile
- backend 디렉토리를 생성한다.
- frontend와 마찬가지로 Dockerfile을 작성하기 위해 에디터를 켠다.
# backend/Dockerfile
FROM python:3.9
WORKDIR /workspace
RUN pip install fastapi uvicorn[standard] --no-cache-dir
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0"]
- 위의 내용을 복사하여 붙여넣는다.
- RUN pip install ... 명령어에 라이브러리 추가할 수 있다.
3.2. Backend script
vim backend/main.py
# backend/main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
- backend의 기본이 되는 script를 작성한다.
- 위의 코드를 붙여넣는다.
4. Docker Compose
vim docker-compose.yaml
- 이제 frontend와 backend를 통합하여 관리할 수 있는 docker-compose 파일을 만들 차례다.
# docker-compose.yaml
version: "3.8"
services:
frontend:
build:
context: frontend/.
dockerfile: Dockerfile
container_name: my-web-frontend
tty: true
ports:
- 3000:3000
volumes:
- ./frontend:/workspace
- ./assets:/assets
command: npm start
backend:
build:
context: backend/.
dockerfile: Dockerfile
container_name: my-web-backend
tty: true
ports:
- 8000:8000
volumes:
- ./backend:/workspace
- ./assets:/assets
command: uvicorn main:app --host 0.0.0.0 --reload
- 이 글에서는 편의상 host port와 container port를 동일하게 설정했다. 상황에 맞게 host port를 바꾸면 된다. (3000:3000 → 13021:3000)
- (volumes) ./assets:/assets: 1.2에서 assets 디렉토리를 생성한 경우만 사용한다.
5. 실행
docker-compose up
- docker-compose를 실행한다.
6. 마치며
- React frontend와 FastAPI backend를 사용하는 web application 개발 환경을 구축했다.
- docker-compose를 사용해 frontend와 backend를 쉽게 관리할 수 있다.
- 다음에는 frontend와 backend간의 통신하는 방법을 다룰 예정이다.
'web' 카테고리의 다른 글
React에서 Form 구현하기 (0) | 2023.05.09 |
---|