-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathsnippets.txt
More file actions
79 lines (51 loc) · 1.92 KB
/
snippets.txt
File metadata and controls
79 lines (51 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
## Security Headers Middleware
@app.middleware("http")
async def add_security_headers(request: Request, call_next):
response = await call_next(request)
response.headers["X-Frame-Options"] = "SAMEORIGIN"
response.headers["X-Content-Type-Options"] = "nosniff"
if "Referrer-Policy" not in response.headers:
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
if request.url.hostname not in ("localhost", "127.0.0.1"):
response.headers["Strict-Transport-Security"] = (
"max-age=63072000; includeSubDomains"
)
return response
## Dockerfile
# BUILD STAGE
FROM python:3.14.4-slim-bookworm AS builder
# Copy UV binary from official image
COPY --from=ghcr.io/astral-sh/uv:0.11.6 /uv /uvx /bin/
WORKDIR /app
# UV Docker optimizations
ENV UV_COMPILE_BYTECODE=1
ENV UV_LINK_MODE=copy
ENV UV_PYTHON_DOWNLOADS=0
# Install dependencies first (cached if unchanged)
COPY pyproject.toml uv.lock ./
RUN uv sync --locked --no-install-project --no-dev
# Copy app code and install project
COPY . ./
RUN uv sync --locked --no-dev
# PRODUCTION STAGE
FROM python:3.14.4-slim-bookworm
WORKDIR /app
# Run as non-root user for security
RUN useradd -m appuser && chown -R appuser:appuser /app
USER appuser
# Copy app and dependencies from builder stage
COPY --from=builder --chown=appuser:appuser /app /app
ENV PATH="/app/.venv/bin:$PATH"
ENV PYTHONUNBUFFERED=1
ENV PORT=8080
# exec replaces shell so fastapi receives SIGTERM for clean shutdown
CMD ["/bin/sh", "-c", "exec fastapi run --host 0.0.0.0 --port \"$PORT\" --proxy-headers --forwarded-allow-ips '*'"]
## Build and Push to Artifact Registry
gcloud builds submit \
--tag us-east4-docker.pkg.dev/YOUR_PROJECT_ID/fastapi-repo/fastapi-app
## Deploy to Cloud Run
gcloud run deploy fastapi-service \
--image us-east4-docker.pkg.dev/YOUR_PROJECT_ID/fastapi-repo/fastapi-app \
--region us-east4 \
--allow-unauthenticated
##