코샵
끄적끄적 코딩 공방
코샵

인기 글

  • 분류 전체보기 (478) N
    • MongoDB (4)
    • 일기장 (4)
    • Unity (138)
      • Tip (41)
      • Project (1)
      • Design Pattern (8)
      • Firebase (6)
      • Asset (2)
    • 파이썬 (127)
      • Basic (40)
      • OpenCV (8)
      • Pandas (15)
      • PyQT (3)
      • SBC(Single Board Computer) (1)
      • 크롤링 (14)
      • Fast API (29)
      • Package (6)
    • Linux (4)
    • C# (97)
      • Algorithm (11)
      • Window (7)
    • TypeScript (47) N
      • CSS (9) N
    • Git (11)
    • SQL (5)
    • Flutter (10)
      • Tip (1)
    • System (1)
    • BaekJoon (6)
    • Portfolio (2)
    • MacOS (1)
    • 유틸리티 (1)
    • 서비스 (6)
    • 자동화 (3)
    • Hobby (10)
      • 물생활 (10)
      • 식집사 (0)
전체 방문자
오늘
어제

최근 댓글

최근 글

반응형
hELLO · Designed By 정상우.
코샵

끄적끄적 코딩 공방

파이썬/Fast API

FastAPI와 Nginx : 웹 서버 구성

2025. 2. 7. 10:54
반응형

Nginx란 무엇인가?

Nginx(엔진엑스)는 고성능 웹 서버이자 리버스 프록시, 로드 밸런서, HTTP 캐시로 사용되는 오픈 소스 소프트웨어입니다. 2004년 Igor Sysoev가 개발한 이후, 현재 전 세계 웹 서버 시장의 상당 부분을 차지하고 있습니다.

주요 특징:

  • 비동기 이벤트 기반 아키텍처
  • 낮은 메모리 사용량
  • 높은 동시성 처리 능력
  • 정적 파일 서빙 최적화

FastAPI에 Nginx가 필요한 이유

리버스 프록시 기능

# nginx.conf
server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

이 설정으로 Nginx는 들어오는 요청을 FastAPI 서버로 전달합니다. 

 

SSL/TLS 종단점 

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    location / {
        proxy_pass http://localhost:8000;
    }
}

 

정적 파일 서빙 

server {
    location /static/ {
        alias /path/to/your/static/files/;
        expires 30d;
        add_header Cache-Control "public, no-transform";
    }
}

 

로드 밸런싱

upstream fastapi_servers {
    server 127.0.0.1:8000;
    server 127.0.0.1:8001;
    server 127.0.0.1:8002;
}

server {
    location / {
        proxy_pass http://fastapi_servers;
    }
}

 

Nginx와 FastAPI 통합 설정 예시

# FastAPI 서버 설정
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
# Nginx 상세 설정
http {
    # 기본 설정
    include mime.types;
    default_type application/octet-stream;
    sendfile on;
    keepalive_timeout 65;

    # GZIP 압축
    gzip on;
    gzip_types text/plain text/css application/json application/javascript;
    
    # 버퍼 설정
    client_body_buffer_size 10K;
    client_header_buffer_size 1k;
    client_max_body_size 8m;
    large_client_header_buffers 2 1k;

    # FastAPI 서버 설정
    upstream fastapi_app {
        server 127.0.0.1:8000;
    }

    server {
        listen 80;
        server_name example.com;

        # SSL 리다이렉션
        return 301 https://$server_name$request_uri;
    }

    server {
        listen 443 ssl;
        server_name example.com;

        # SSL 설정
        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers HIGH:!aNULL:!MD5;

        # 보안 헤더
        add_header X-Frame-Options "SAMEORIGIN";
        add_header X-XSS-Protection "1; mode=block";
        add_header X-Content-Type-Options "nosniff";

        # 정적 파일
        location /static/ {
            alias /path/to/static/;
            expires 30d;
            add_header Cache-Control "public, no-transform";
        }

        # FastAPI
        location / {
            proxy_pass http://fastapi_app;
            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;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;

            # 타임아웃 설정
            proxy_connect_timeout 60s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
        }
    }
}

Nginx가 제공하는 이점

  1. 보안 강화
    • SSL/TLS 종단점 관리
    • DDoS 보호
    • 요청 제한 기능
  2. 성능 최적화
    • 정적 파일 캐싱
    • 압축 기능
    • 요청 버퍼링
  3. 안정성
    • 로드 밸런싱
    • 헬스 체크
    • 장애 조치
  4. 유연성
    • URL 재작성
    • 요청/응답 헤더 수정
    • 다중 도메인 지원

FastAPI만으로도 웹 서버를 구축할 수 있지만, Nginx를 함께 사용하면 더 안정적이고 확장 가능한 아키텍처를 구성할 수 있습니다. 특히 프로덕션 환경에서는 Nginx의 다양한 기능이 필수적이라고 할 수 있습니다.

저작자표시 비영리 변경금지 (새창열림)

'파이썬 > Fast API' 카테고리의 다른 글

pyinstrument : 성능 최적화를 위한 프로파일링  (0) 2025.02.11
FastAPI 쿼리 매개변수  (0) 2025.02.09
FastAPI 프로젝트 배포 자동화 가이드 Part 3: 무중단 배포와 모니터링  (0) 2025.02.05
FastAPI 프로젝트 배포 자동화 가이드 Part 2: CD 파이프라인과 서버 배포  (2) 2025.02.04
프로젝트 배포 자동화 가이드 Part 1: 개발 환경 구성  (1) 2025.02.03
    '파이썬/Fast API' 카테고리의 다른 글
    • pyinstrument : 성능 최적화를 위한 프로파일링
    • FastAPI 쿼리 매개변수
    • FastAPI 프로젝트 배포 자동화 가이드 Part 3: 무중단 배포와 모니터링
    • FastAPI 프로젝트 배포 자동화 가이드 Part 2: CD 파이프라인과 서버 배포
    코샵
    코샵
    나의 코딩 일기장

    티스토리툴바