본문 바로가기
MLOps/배포

우분투에서 도커로 FastAPI 환경 구축하기

by 해피ing 2024. 1. 24.
반응형

 

FastAPI란?

 

FastAPI는 파이썬 프로그래밍 언어에 기초한 API를 빌드하기 위한 웹 프레임워크로 Swagger UI와 Redoc 사용이 가능합니다.

 

도커 기반 FastAPI 설치

 

설치에 필요한 폴더와 파일 구조는 다음과 같습니다.

 

example/
├── app
│   └── main.py
├── docker-compose.yml
├── Dockerfile
└── requirements.tx

 

FastAPI 실행 시 Swagger UI 화면에서 보여지는 모습은 app/main.py에서 설정할 수 있습니다.

 

server@gpu:/$ sudo mkdir app
server@gpu:/$ sudo vim app/main.py

from typing import Union
from fastapi import FastAPI

app = FastAPI()

@app.get('/')
def read_root():
    return {'Hello': 'World'}

@app.get('/items/{item_id}')
def read_item(item_id: int, q: Union[str, None] = None):
    return {'item_id': item_id, 'q': q}

 

 

도커 이미지 생성에 필요한 Dockerfile은 FROM의 GPU CUDA 정보는 상황에 따라 달라질 수 있습니다.

 

server@gpu:/$ sudo vim Dockerfile

FROM nvidia/cuda:12.0.0-devel-ubuntu20.04

WORKDIR /app

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

ARG DEBIAN_FRONTEND=noninteractive
RUN apt update && \
    apt install -y python3 python3-pip libgl1-mesa-glx libglib2.0-0 tzdata

RUN ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime

COPY requirements.txt /tmp/requirements.txt
RUN pip install --no-cache-dir -r /tmp/requirements.txt

COPY . .

 

FastAPI 설치에 필요한 요구 조건은 requirements.txt에서 확인할 수 있습니다.

 

server@gpu:/$ sudo vim requirements.txt

fastapi==0.89.1
uvicorn==0.20.0
ultralytics==8.0.42
pandas
numpy
scikit-learn
seaborn
matplotlib
opencv-python
python-multipart

 

도커에서 FastAPI 실행은 docker-compose.yml에서 설정할 수 있습니다.

 

server@gpu:/$ sudo vim docker-compose.yml

version: '3.8'

services:
  web:
    build: .
    command: uvicorn app.main:app --host 0.0.0.0
    volumes:
      - ./:/app
    ports:
      - 8000:8000
      
server@gpu:/$ docker compose up -d

[+] Building 0.2s (12/12) FINISHED                                                                        docker:default
 => [web internal] load build definition from Dockerfile                                                            0.0s
 => => transferring dockerfile: 449B                                                                                0.0s
 => [web internal] load .dockerignore                                                                               0.0s
 => => transferring context: 2B                                                                                     0.0s
 => [web internal] load metadata for docker.io/nvidia/cuda:12.0.0-devel-ubuntu20.04                                 0.0s
 => [web 1/7] FROM docker.io/nvidia/cuda:12.0.0-devel-ubuntu20.04                                                   0.0s
 => [web internal] load build context                                                                               0.0s
 => => transferring context: 826B                                                                                   0.0s
 => CACHED [web 2/7] WORKDIR /app                                                                                   0.0s
 => CACHED [web 3/7] RUN apt update &&     apt install -y python3 python3-pip libgl1-mesa-glx libglib2.0-0 tzdata   0.0s
 => CACHED [web 4/7] RUN ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime                                       0.0s
 => CACHED [web 5/7] COPY requirements.txt /tmp/requirements.txt                                                    0.0s
 => CACHED [web 6/7] RUN pip install --no-cache-dir -r /tmp/requirements.txt                                        0.0s
 => [web 7/7] COPY . .                                                                                              0.0s
 => [web] exporting to image                                                                                        0.0s
 => => exporting layers                                                                                             0.0s
 => => writing image sha256:bbdf0f9eb7fd41150005d4b33293aee3b806d3b2b5a7ae84c4273cb49e16ef32                        0.0s
 => => naming to docker.io/library/example-web                                                                      0.0s
[+] Running 2/2
 ✔ Network example_default  Created                                                                                 0.1s
 ✔ Container example-web-1  Created                                                                                 0.1s

 

실행 중인 Docker FastAPI이 다음과 같이 출력되면 Swagger UI와 Redoc를 사용할 수 있습니다.

 

server@gpu:/$ docker compose ps

NAME            IMAGE         COMMAND                                                                  SERVICE   CREATED         STATUS         PORTS
example-web-1   example-web   "/opt/nvidia/nvidia_entrypoint.sh uvicorn app.main:app --host 0.0.0.0"   web       5 seconds ago   Up 4 seconds   0.0.0.0:8000->8000/tcp, :::8000->8000/tcp

 

FastAPI Redoc 접속

 

접속 주소는 http://localhost:8000/redoc 입니다.

 

 

FastAPI Swagger UI 접속

 

접속 주소는 http://localhost:8000/docs 입니다.

 

 

 

반응형

'MLOps > 배포' 카테고리의 다른 글

FastAPI 로그 관리하기  (2) 2024.01.30
FastAPI로 데이터 업로드하기  (0) 2024.01.30