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:
+19
-9
@@ -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,9 +44,9 @@ 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:
|
||||||
mysql_data:
|
mysql_data:
|
||||||
uploads_data:
|
uploads_data:
|
||||||
|
|||||||
+71
-13
@@ -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) ─────────
|
||||||
proxy_pass http://app:8000;
|
location /assets/ {
|
||||||
proxy_http_version 1.1;
|
root /usr/share/nginx/html;
|
||||||
proxy_set_header Host $host;
|
expires 1y;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
add_header Cache-Control "public, immutable";
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
try_files $uri =404;
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
|
||||||
proxy_set_header Connection "upgrade";
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
# ── 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_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;
|
||||||
|
# Allow larger responses for file downloads
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+29
-48
@@ -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,34 +22,34 @@ 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
|
||||||
app.include_router(auth.router)
|
app.include_router(auth.router)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
log.exception("Failed to load auth router: %s", exc)
|
log.exception("Failed to load auth router: %s", exc)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from app.routers import upload # type: ignore
|
from app.routers import upload # type: ignore
|
||||||
app.include_router(upload.router)
|
app.include_router(upload.router)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
log.exception("Failed to load upload router: %s", exc)
|
log.exception("Failed to load upload router: %s", exc)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from app.routers import contact # type: ignore
|
from app.routers import contact # type: ignore
|
||||||
app.include_router(contact.router)
|
app.include_router(contact.router)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
log.exception("Failed to load contact router: %s", exc)
|
log.exception("Failed to load contact router: %s", exc)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from app.routers import review # type: ignore
|
from app.routers import review # type: ignore
|
||||||
app.include_router(review.router)
|
app.include_router(review.router)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
log.exception("Failed to load review router: %s", exc)
|
log.exception("Failed to load review router: %s", exc)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from app.routers import chatbot # type: ignore
|
from app.routers import chatbot # type: ignore
|
||||||
app.include_router(chatbot.router)
|
app.include_router(chatbot.router)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
log.exception("Failed to load chatbot router: %s", exc)
|
log.exception("Failed to load chatbot router: %s", exc)
|
||||||
@@ -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")
|
||||||
)
|
)
|
||||||
|
DIST_DIR = os.path.join(FRONTEND_DIR, "dist")
|
||||||
|
SPA_INDEX = os.path.join(DIST_DIR, "index.html")
|
||||||
|
|
||||||
|
|
||||||
def mount_if_exists(route: str, subdir: str, name: str):
|
def _mount_if_exists(route: str, path: str, name: str) -> None:
|
||||||
path = os.path.join(FRONTEND_DIR, subdir)
|
|
||||||
if os.path.isdir(path):
|
if os.path.isdir(path):
|
||||||
app.mount(route, StaticFiles(directory=path), name=name)
|
app.mount(route, StaticFiles(directory=path), name=name)
|
||||||
log.info("Mounted static %s -> %s", route, path)
|
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("/css", os.path.join(DIST_DIR, "css"), "css")
|
||||||
mount_if_exists("/images", "dist/images", "images")
|
_mount_if_exists("/assets", os.path.join(DIST_DIR, "assets"), "assets")
|
||||||
mount_if_exists("/css", "dist/css", "css")
|
_mount_if_exists("/images", os.path.join(DIST_DIR, "images"), "images")
|
||||||
|
|
||||||
# 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)
|
|
||||||
|
|
||||||
|
# Ensure uploads directory exists
|
||||||
UPLOAD_DIR = os.path.abspath(os.path.join(FRONTEND_DIR, "..", "uploads"))
|
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)
|
||||||
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")
|
|
||||||
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")
|
|
||||||
|
|
||||||
|
|
||||||
# ─────────────────────────────────────────────
|
# ─────────────────────────────────────────────
|
||||||
# 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"])
|
||||||
@@ -147,8 +125,11 @@ def spa_fallback(full_path: str):
|
|||||||
SPA_INDEX,
|
SPA_INDEX,
|
||||||
headers={
|
headers={
|
||||||
"Cache-Control": "no-store, no-cache, must-revalidate",
|
"Cache-Control": "no-store, no-cache, must-revalidate",
|
||||||
"Pragma": "no-cache",
|
"Pragma": "no-cache",
|
||||||
"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.
Reference in New Issue
Block a user