파이썬/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의 다양한 기능이 필수적이라고 할 수 있습니다.