fix: production deployment fixes

- .env: MYSQL_HOST=db (Docker service name, not localhost)
- .env: ALLOWED_ORIGINS includes bookkeepro.net + IP
- docker-compose.yml: add nginx service, fix MySQL user/password env vars,
  expose app on port 8000 internally only, nginx on port 80
- nginx/default.conf: serve /css /assets /images directly from dist,
  proxy /api/* to FastAPI, SPA fallback via try_files
- main.py: remove duplicate /dist mount, hide API docs in production,
  clean up static mount logic
- requirements.txt: add pypdf==4.3.1 (was missing, used by ai.py)
This commit is contained in:
Atharv1705
2026-08-10 10:30:00 +05:30
parent 9c7f25e06f
commit 1170ea38fc
4 changed files with 119 additions and 70 deletions
+18 -8
View File
@@ -1,4 +1,16 @@
services: services:
nginx:
image: nginx:1.25-alpine
ports:
- "80:80"
volumes:
- ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
- ./frontend/dist:/usr/share/nginx/html:ro
- uploads_data:/app/uploads:ro
depends_on:
- app
restart: unless-stopped
app: app:
build: build:
context: . context: .
@@ -9,10 +21,10 @@ services:
MYSQL_HOST: db MYSQL_HOST: db
MYSQL_PORT: 3306 MYSQL_PORT: 3306
MYSQL_DATABASE: ${MYSQL_DATABASE:-bookkeepprodb} MYSQL_DATABASE: ${MYSQL_DATABASE:-bookkeepprodb}
MYSQL_USER: ${MYSQL_USER:-bookkeep} MYSQL_USER: ${MYSQL_USER:-root}
MYSQL_PASSWORD: ${MYSQL_PASSWORD:-bookkeepro_pass} MYSQL_PASSWORD: ${MYSQL_PASSWORD:-***REDACTED_PASSWORD***}
ports: expose:
- "8000:8000" - "8000"
depends_on: depends_on:
db: db:
condition: service_healthy condition: service_healthy
@@ -20,12 +32,10 @@ services:
volumes: volumes:
- uploads_data:/app/uploads - uploads_data:/app/uploads
db: db:
image: mysql:8.4 image: mysql:8.4
environment: environment:
MYSQL_ROOT_PASSWORD: ${MYSQL_PASSWORD:-rootpassword} MYSQL_ROOT_PASSWORD: ${MYSQL_PASSWORD:-***REDACTED_PASSWORD***}
MYSQL_DATABASE: ${MYSQL_DATABASE:-bookkeepprodb} MYSQL_DATABASE: ${MYSQL_DATABASE:-bookkeepprodb}
volumes: volumes:
- mysql_data:/var/lib/mysql - mysql_data:/var/lib/mysql
@@ -34,7 +44,7 @@ services:
interval: 10s interval: 10s
timeout: 5s timeout: 5s
retries: 10 retries: 10
start_period: 20s start_period: 30s
restart: unless-stopped restart: unless-stopped
volumes: volumes:
+64 -6
View File
@@ -2,22 +2,80 @@ server {
listen 80; listen 80;
server_name _; server_name _;
client_max_body_size 25m; # Max upload size — matches backend 10MB limit with buffer
client_max_body_size 15m;
location ~ ^/(css|js|images)/ { # ── Static CSS (served directly from dist, no FastAPI hop) ───────────────
location /css/ {
root /usr/share/nginx/html; root /usr/share/nginx/html;
expires 30d; expires 7d;
add_header Cache-Control "public, no-transform"; add_header Cache-Control "public, no-transform";
try_files $uri =404;
} }
location / { # ── Vite JS/CSS bundle assets (hashed filenames — cache forever) ─────────
location /assets/ {
root /usr/share/nginx/html;
expires 1y;
add_header Cache-Control "public, immutable";
try_files $uri =404;
}
# ── Static images served from dist ───────────────────────────────────────
location /images/ {
root /usr/share/nginx/html;
expires 7d;
add_header Cache-Control "public, no-transform";
try_files $uri =404;
}
# ── Favicon and root-level static files ──────────────────────────────────
location = /favicon.svg {
root /usr/share/nginx/html;
expires 7d;
}
location = /icons.svg {
root /usr/share/nginx/html;
expires 7d;
}
# ── User-uploaded files (documents stored on VPS disk) ───────────────────
# Proxied through FastAPI for auth token validation — never served directly
location /api/upload/file/ {
proxy_pass http://app:8000; proxy_pass http://app:8000;
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade; # Allow larger responses for file downloads
proxy_set_header Connection "upgrade"; proxy_buffering off;
proxy_read_timeout 120s;
}
# ── All API routes → FastAPI ──────────────────────────────────────────────
location /api/ {
proxy_pass http://app:8000;
proxy_http_version 1.1;
proxy_set_header Host $host;
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_read_timeout 60s;
proxy_send_timeout 60s;
}
# ── Health check (bypass FastAPI for load balancer pings) ────────────────
location = /health {
proxy_pass http://app:8000;
proxy_set_header Host $host;
}
# ── SPA fallback — serve index.html for all other routes ─────────────────
# React Router handles the actual routing client-side
location / {
root /usr/share/nginx/html;
index index.html;
try_files $uri $uri/ /index.html;
} }
} }
+26 -45
View File
@@ -4,8 +4,7 @@ from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse from fastapi.responses import FileResponse
from slowapi import Limiter, _rate_limit_exceeded_handler from slowapi import _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded from slowapi.errors import RateLimitExceeded
from app.limiter import limiter from app.limiter import limiter
from app import models from app import models
@@ -13,9 +12,9 @@ from app.db import engine
log = logging.getLogger("uvicorn.error") log = logging.getLogger("uvicorn.error")
app = FastAPI(title="BookKeepPro API") app = FastAPI(title="BookKeepPro API", docs_url=None, redoc_url=None) # hide docs in production
# Rate limiter — import from limiter.py to avoid circular imports # Rate limiter
app.state.limiter = limiter app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
@@ -23,7 +22,7 @@ app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
models.Base.metadata.create_all(bind=engine) models.Base.metadata.create_all(bind=engine)
# ───────────────────────────────────────────── # ─────────────────────────────────────────────
# Routers — each isolated so one failure never kills the others # Routers — isolated so one failure never kills the others
# ───────────────────────────────────────────── # ─────────────────────────────────────────────
try: try:
from app.routers import auth # type: ignore from app.routers import auth # type: ignore
@@ -76,68 +75,47 @@ app.add_middleware(
) )
# ───────────────────────────────────────────── # ─────────────────────────────────────────────
# Static file mounts # Static files — fallback for when nginx is not in front
# In production, nginx serves /css, /assets, /images directly
# ───────────────────────────────────────────── # ─────────────────────────────────────────────
FRONTEND_DIR = os.path.abspath( FRONTEND_DIR = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "..", "..", "frontend") os.path.join(os.path.dirname(__file__), "..", "..", "..", "frontend")
) )
def mount_if_exists(route: str, subdir: str, name: str):
path = os.path.join(FRONTEND_DIR, subdir)
if os.path.isdir(path):
app.mount(route, StaticFiles(directory=path), name=name)
log.info("Mounted static %s -> %s", route, path)
else:
log.debug("Static directory not found, skipping: %s", path)
mount_if_exists("/js", "dist/js", "js")
mount_if_exists("/images", "dist/images", "images")
mount_if_exists("/css", "dist/css", "css")
# Mount Vite build assets (JS bundles, hashed chunks)
DIST_ASSETS = os.path.join(FRONTEND_DIR, "dist", "assets")
if os.path.isdir(DIST_ASSETS):
app.mount("/assets", StaticFiles(directory=DIST_ASSETS), name="assets")
log.info("Mounted Vite assets -> %s", DIST_ASSETS)
UPLOAD_DIR = os.path.abspath(os.path.join(FRONTEND_DIR, "..", "uploads"))
if not os.path.exists(UPLOAD_DIR):
os.makedirs(UPLOAD_DIR, exist_ok=True)
log.info("FRONTEND_DIR resolved to: %s", FRONTEND_DIR)
log.info("CSS dir exists: %s", os.path.isdir(os.path.join(FRONTEND_DIR, "css")))
DIST_DIR = os.path.join(FRONTEND_DIR, "dist") DIST_DIR = os.path.join(FRONTEND_DIR, "dist")
SPA_INDEX = os.path.join(DIST_DIR, "index.html") SPA_INDEX = os.path.join(DIST_DIR, "index.html")
# Mount the Vite dist folder for hashed static assets not already mounted above
# (favicon, icons.svg, etc.)
if os.path.isdir(DIST_DIR):
# Serve root-level static assets that Vite places at dist/
app.mount("/dist", StaticFiles(directory=DIST_DIR), name="dist_root")
def _mount_if_exists(route: str, path: str, name: str) -> None:
if os.path.isdir(path):
app.mount(route, StaticFiles(directory=path), name=name)
log.info("Mounted static %s → %s", route, path)
_mount_if_exists("/css", os.path.join(DIST_DIR, "css"), "css")
_mount_if_exists("/assets", os.path.join(DIST_DIR, "assets"), "assets")
_mount_if_exists("/images", os.path.join(DIST_DIR, "images"), "images")
# Ensure uploads directory exists
UPLOAD_DIR = os.path.abspath(os.path.join(FRONTEND_DIR, "..", "uploads"))
os.makedirs(UPLOAD_DIR, exist_ok=True)
# ───────────────────────────────────────────── # ─────────────────────────────────────────────
# Ops endpoints # Ops
# ───────────────────────────────────────────── # ─────────────────────────────────────────────
@app.get("/health", tags=["ops"]) @app.get("/health", tags=["ops"])
def health(): def health():
"""Health check for monitoring and load balancers."""
return {"status": "ok"} return {"status": "ok"}
@app.post("/logout", tags=["auth"]) @app.post("/logout", tags=["auth"])
def logout(): def logout():
# JWT is stateless — token is invalidated client-side by clearing localStorage
return {"message": "Logged out"} return {"message": "Logged out"}
# ───────────────────────────────────────────── # ─────────────────────────────────────────────
# SPA catch-all — serve index.html for every non-API GET route # SPA catch-all — serve index.html for all non-API routes
# so React Router handles client-side navigation on direct URL access # React Router handles client-side navigation
# ───────────────────────────────────────────── # ─────────────────────────────────────────────
@app.get("/{full_path:path}", tags=["frontend"]) @app.get("/{full_path:path}", tags=["frontend"])
@@ -151,4 +129,7 @@ def spa_fallback(full_path: str):
"Expires": "0", "Expires": "0",
}, },
) )
raise HTTPException(status_code=404, detail="Frontend not built. Run 'npm run build' in /frontend.") raise HTTPException(
status_code=404,
detail="Frontend not built. Run 'npm run build' in /frontend.",
)
Binary file not shown.