Nginx로 FastAPI 배포하기

김지원·2023년 1월 2일
3

Backend

목록 보기
1/4

🧩 FastAPI - Gunicorn 사용하기

Uvicorn을 사용하여 FastAPI를 구동할 수 있다.
하지만 Uvicorn의 경우, Single Process로만 동작하기 때문에
Production(배포) 환경에서는 Multi Process를 사용하고 관리할 수 있는 WSGI 서버인 💡Gunicorn을 이용하여 서버를 구동하는 것이 좋다.

Uvicorn에서 Gunicorn worker class를 제공한다.
따라서 Multi Process 관리(Gunicorn) + 강력한 성능(Uvicorn)을 모두 활용하여 ASGI 서버를 구동할 수 있다.

gunicorn -k uvicorn.workers.UvicornWorker --access-logfile ./gunicorn-access.log main:app --bind 0.0.0.0:8000 --workers 2 --daemon
  • -k uvicorn.workers.UvicornWorker: Uvicorn worker 클래스 사용
  • -access-logfile ./gunicorn-access.log: Gunicorn 로그 파일 기록
  • main:app: main.py의 app을 실행
  • -workers 2: worker process 개수 설정, 통상 CPU 코어 개수 * 2로 설정한다.
  • -daemon: Gunicorn을 백그라운드로 구동
  • -bind 0.0.0.0:8000: 8000 포트에 서버를 연결
ps -ef | grep gunicorn

위 명령어로 Gunicorn이 정상적으로 실행되었는지 확인해보자.

🧩 Gunicorn 서비스로 등록하기

Gunicorn을 서비스로 등록하는 이유는 Gunicorn의 시작, 중지를 쉽게 할 수 있고 서버 재부팅 시 Gunicorn을 자동으로 실행할 수 있기 때문이다.

📝 서비스 파일 작성하기

  • 경로: /etc/systemd/system/myapi.service
[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=ubuntu
Group=ubuntu
WorkingDirectory=/home/{프로젝트 경로}
ExecStart=/home/{gunicorn 경로}/gunicorn \
          main:app \
          --workers 2 \
          --worker-class uvicorn.workers.UvicornWorker \
          --bind unix:/tmp/myapi.sock
[Install]
WantedBy=multi-user.target
  • 시작
sudo systemctl start myapi.service
  • 종료
sudo systemctl stop myapi.service
  • 재시작
sudo systemctl restart myapi.service

🧩 서버 로깅 적용하기

📝 Gunicorn 서비스 파일 수정

  • 경로: /etc/systemd/system/myapi.service
    -log-config /home/ubuntu/projects/myapi/logs/uvicorn_log.ini 부분을 아래처럼 추가해주면 된다.

-log-config 옵션을 추가하여 Gunicorn의 로그를 출력할 수 있다.

...
ExecStart=/home/ubuntu/venvs/myapi/bin/gunicorn \
          main:app \
          --workers 2 \
          --worker-class uvicorn.workers.UvicornWorker \
          --bind unix:/tmp/myapi.sock \
          --log-config /home/ubuntu/projects/myapi/logs/uvicorn_log.ini
...

🧩 Nginx 설정하기

  • /etc/nginx/nginx.conf: nginx의 메인 설정 파일 경로

📝 nginx config 파일 작성

configuration 파일은 2가지의 directives(지시어) 형태로 설정 가능하다.

  • simple directive: 이름, 값이 있고 세미클론(;)으로 끝난다.
  • block directive: simple directive의 구조에 블록("{", "}") 을 감싼 형태의 지시어이다. 해당 directive 안에 또 다른 block directive가 포함될 수 있다.
  • include 지시어: 특정 파일을 포함하는 기능 수행
http {
	include		/etc/nginx/mime.types;
    include		/etc/nginx/conf.d/*.conf;
}

/etc/nginx/sites-available 경로에 fastapi.conf 파일을 생성한다.

sudo nano /etc/nginx/sites-available/fastapi.conf

fastapi.conf 파일 내용

나의 경우, frontend 는 내 컴퓨터에서 구현했기 때문에 fastAPI 서버 관련 설정을 추가해줬다.

server {
        listen 80;
        server_name {서버IP주소 또는 도메인 주소};
        
        location /similarity {
                proxy_pass http://localhost:8005;
                proxy_redirect off;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
}
  • server_name: 자신의 서버 주소 혹은 도메인 주소입력
  • 띄우고 싶은 html 파일이 있다면 경로 location / 내부에 작성해준다.
    예시)
	location / {
    	root {파일 경로}
        index index.html;
    }

📝 심볼릭 링크 생성

sudo ln -s /etc/nginx/sites-available/fastapi.conf /etc/nginx/sites-enable/fastapi.conf 

서버 IP주소로 접속하면 index.html 페이지로 접속되는 것을 확인할 수 있다.

참고
https://wikidocs.net/177269
https://icarus8050.tistory.com/57
https://velog.io/@svstar94/Frontend-Backend-%EC%84%9C%EB%B2%84-AWS-EC2%EB%A1%9C-%EB%B0%B0%ED%8F%AC%ED%95%98%EA%B8%B0-https-%EC%84%A4%EC%A0%95%EA%B9%8C%EC%A7%80

profile
Make your lives Extraordinary!

1개의 댓글

comment-user-thumbnail
6일 전

소켓으로 gunicorn을 띄우는데 nginx에서는 포트를 바인딩한다고요?

답글 달기