Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions app/api/health.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# app/api/health.py
from fastapi import APIRouter

router = APIRouter()


@router.get("/health")
async def health_check():
return {"status": "ok", "message": "Service is healthy"}
23 changes: 23 additions & 0 deletions app/core/port.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

default Port를 30000번대로 설정하는 건 어떻게 생각하시나요??
이유는 8080포트는 개발할때 주로 사용하는 포트이므로 해당 포트가 비어있더라도 저희가 선점한다면 사용자가 process를 강제로 내릴 가능성도 존재한다고 생각합니다.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네 저도 30000번대 고정이 나을 것 같습니다.
동적할당으로 받게되면 프론트쪽으로 정보전달이 어려울 것 같으니 잘 안쓰는 5자리 포트 사용을 하는 게 좋겠네요.

Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# app/core/port.py

import os
import socket


def get_available_port(default: int = 8000) -> int:
"""
환경변수 'PORT'가 존재하면 해당 포트를 사용하고,
없다면 시스템이 할당한 사용 가능한 포트를 반환합니다.
"""
port_from_env = os.getenv("PORT")

if port_from_env:
print(f"Using port from environment variable: {port_from_env}")
return int(port_from_env)

# 포트 0 바인딩 → 시스템이 사용 가능한 포트 할당
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("0.0.0.0", 0))
assigned_port = s.getsockname()[1]
print(f"Dynamically assigned port: {assigned_port}")
return assigned_port
31 changes: 8 additions & 23 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,24 @@
# main.py
import os
import socket # 소켓 모듈 임포트

import uvicorn
from fastapi import FastAPI

from app.api import health # 헬스 체크
from app.core.port import get_available_port # 동적 포트 할당

app = FastAPI()

# 헬스 체크 라우터
app.include_router(health.router)


@app.get("/")
async def read_root():
return {"message": "Hello, FastAPI Backend!"}


@app.get("/health")
async def health_check():
return {"status": "ok", "message": "Service is healthy"}


# 이 부분이 추가된 동적 포트 할당 로직입니다.
if __name__ == "__main__":
# 1. 환경 변수 'PORT'가 있으면 해당 포트를 사용합니다.
# 2. 없으면 사용 가능한 임시 포트를 찾습니다.
port_from_env = os.getenv("PORT")

if port_from_env:
port = int(port_from_env)
print(f"Using port from environment variable: {port}")
else:
# 시스템에서 사용 가능한 임시 포트를 찾습니다.
# 포트 0을 바인딩하면 운영체제가 사용 가능한 포트를 할당해 줍니다.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("0.0.0.0", 0)) # 0.0.0.0에 포트 0을 바인딩
port = s.getsockname()[1] # 할당된 포트 번호 가져오기
print(f"Dynamically assigned port: {port}")

# 동적 할당 로직
port = get_available_port()
# Uvicorn 서버를 시작합니다.
uvicorn.run(app, host="0.0.0.0", port=port)