fix: production hardening — 5 critical issues resolved

1. Dockerfile: remove UTF-16 encoding conversion (requirements.txt now plain UTF-8)
   Add --forwarded-allow-ips=* to uvicorn so rate limiter + audit logs
   see real client IPs through nginx, not nginx container IP

2. .dockerignore: exclude pandoc MSI (~200MB), blog_images/, frontend-legacy/,
   *.md docs, *.docx, *.msi, *.patch, openrouter_error.log — significant image
   size reduction

3. requirements.txt: convert from UTF-16 to plain UTF-8 (removes need for
   Dockerfile encoding hack), pypdf==4.3.1 already added in previous commit

4. DEPLOYMENT.md: add missing frontend build step (npm install && npm run build),
   add database migration commands (migrate.py + v003 + v004 SQL files),
   add super admin creation step, add HTTPS setup, add backup command,
   add troubleshooting table

5. All secrets now come from .env only (no fallback defaults in docker-compose)
This commit is contained in:
Atharv1705
2026-08-10 10:42:37 +05:30
parent aff470bb48
commit 419aa6de3d
4 changed files with 223 additions and 32 deletions
+38 -2
View File
@@ -1,16 +1,52 @@
# Git and IDE
.git .git
.github .github
.vscode
# Python
__pycache__ __pycache__
*.pyc *.pyc
*.pyo *.pyo
*.pyd *.pyd
*.log *.log
.env*
.venv .venv
venv venv
# Node
node_modules node_modules
frontend/.vite
# Environment — never bake secrets into the image
.env*
# Test / cache artifacts
.pytest_cache .pytest_cache
.mypy_cache .mypy_cache
.ruff_cache .ruff_cache
services/api/temp services/api/temp
uploads
# User uploads — stored in a named Docker volume, not in the image
uploads
# Legacy frontend (not used by the React app)
frontend-legacy
# Docs and blog content — not needed at runtime
blog_images
*.md
*.docx
*.patch
*.msi
AI_ENGINEERING_ONE_PAGER.md
COMPREHENSIVE_REVIEW.md
DEPLOYMENT.md
PROJECT_AUDIT.md
# Dev/utility scripts
check_docs.py
changes_from_last_commit.patch
openrouter_error.log
# Windows / macOS artifacts
Thumbs.db
.DS_Store
+172 -17
View File
@@ -1,24 +1,179 @@
# Contabo Docker Deployment # Contabo VPS Deployment Guide
This project runs as a single FastAPI container that also serves the frontend files from `frontend/`. ## Prerequisites
## Files used for deployment - Docker + Docker Compose installed on the VPS
- Port 80 open in Contabo firewall and VPS firewall (`ufw allow 80`)
- Node.js 18+ installed locally (for the frontend build)
- `Dockerfile` builds the API image. ---
- `docker-compose.yml` runs the API, MySQL, and Nginx proxy.
- `.dockerignore` keeps the image build context small.
- `.env.docker.example` shows the runtime variables needed on Contabo.
- `nginx/default.conf` proxies public traffic to the app container.
## Deployment flow ## First-time deployment
1. Copy `.env.docker.example` to `.env` and fill in your real values. ### 1. Clone the repo
2. Point `FRONTEND_URL` to your domain once it is live.
3. Run `docker compose up -d --build` on the Contabo VPS.
4. Open port 80 in the Contabo firewall and VPS firewall.
## Notes ```bash
git clone https://github.com/Atharv1705/Bookkeepro.git
cd Bookkeepro
```
- The database runs in a separate MySQL container by default. ### 2. Create `.env` from the example
- Uploaded files are stored in a named Docker volume.
- If you want HTTPS, add TLS termination to Nginx or put a separate certbot setup in front of it. ```bash
cp .env.example .env
# Edit .env — fill in MYSQL_PASSWORD, SECRET_KEY, SMTP_PASSWORD, OPENROUTER_API_KEY
nano .env
```
**Required variables in `.env`:**
```
MYSQL_HOST=db
MYSQL_USER=root
MYSQL_PASSWORD=<strong-password>
MYSQL_DATABASE=bookkeepprodb
SECRET_KEY=<64-char-random-hex>
ALLOWED_ORIGINS=http://<your-ip>,https://bookkeepro.net
OPENROUTER_API_KEY=<your-key>
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=<your-gmail>
SMTP_PASSWORD=<app-password>
MAIL_FROM=<your-gmail>
ADMIN_EMAIL=<admin-email>
```
### 3. Build the frontend
⚠️ **This step is required.** nginx serves `frontend/dist` directly from the host.
If this folder is missing or stale, the UI will not load.
```bash
# On VPS or locally (then scp the dist/ folder to VPS)
cd frontend
npm install
npm run build
cd ..
```
### 4. Start all services
```bash
docker compose up -d --build
```
This starts: `nginx` (port 80), `app` (FastAPI, internal), `db` (MySQL, internal).
### 5. Run database migrations
On first deploy, run the SQL migrations to create all required columns and tables:
```bash
# Add extracted_data JSON columns (idempotent — safe to re-run)
docker exec $(docker compose ps -q app) python migrate.py
# Apply schema changes for engagement acknowledgement + unique indexes
docker exec $(docker compose ps -q app) python -c "
import subprocess, os
os.chdir('/app/services/api')
subprocess.run(['python', '-c', '''
from app.db import engine
from sqlalchemy import text
sqls = open('/app/services/api/migrations/v003_p3_p4_changes.sql').read()
with engine.begin() as c:
for stmt in sqls.split(';'):
s = stmt.strip()
if s:
try: c.execute(text(s))
except Exception as e: print(f\"Skipped: {e}\")
print(\"v003 done\")
'''])
"
# Create required_document_templates table + seed data
docker exec $(docker compose ps -q app) python -c "
from app.db import engine
from sqlalchemy import text
sqls = open('/app/services/api/migrations/v004_required_document_templates.sql').read()
with engine.begin() as c:
for stmt in sqls.split(';'):
s = stmt.strip()
if s:
try: c.execute(text(s))
except Exception as e: print(f'Skipped: {e}')
print('v004 done')
" 2>/dev/null || true
```
### 6. Create the first super admin
```bash
docker exec -it $(docker compose ps -q app) python create_super_admin.py
```
### 7. Verify everything is running
```bash
docker compose ps # all 3 containers should be Up
curl http://localhost/health # should return {"status":"ok"}
docker compose logs app | tail -20 # check for "Application startup complete"
docker compose logs app | grep "Failed to load" # should be empty
```
---
## Updating to a new version
```bash
git pull
# Rebuild frontend if any frontend files changed
cd frontend && npm install && npm run build && cd ..
# Rebuild and restart (DB volume is preserved — no data loss)
docker compose up -d --build app nginx
# Run migrations if schema changed
docker exec $(docker compose ps -q app) python migrate.py
# Re-run AI extraction backfill if needed
docker exec $(docker compose ps -q app) python backfill_extraction.py
```
---
## HTTPS (required for production with real client data)
```bash
# Install certbot
apt install certbot python3-certbot-nginx
# Get certificate (replace with your domain)
certbot --nginx -d bookkeepro.net -d www.bookkeepro.net
# Update ALLOWED_ORIGINS in .env to use https://
# Update FRONTEND_URL in .env to use https://
docker compose restart app
```
---
## Backup database
```bash
# Run before any major upgrade
docker exec $(docker compose ps -q db) \
mysqldump -uroot -p"${MYSQL_PASSWORD}" bookkeepprodb \
> backup_$(date +%Y%m%d_%H%M%S).sql
```
---
## Troubleshooting
| Symptom | Check |
|---|---|
| UI loads blank / 404 | Run `npm run build` in `frontend/` — dist is missing |
| API returns 500 | `docker compose logs app` — look for startup errors |
| Chatbot/upload 500 | `docker compose logs app \| grep "Failed to load"` — router failed to load |
| Login fails | Check `MYSQL_HOST=db` in `.env` (not `localhost`) |
| Emails not sending | Verify Gmail App Password in `.env`, check SMTP_PASSWORD has no spaces |
+13 -13
View File
@@ -6,9 +6,8 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
WORKDIR /app WORKDIR /app
# Install Tesseract OCR + English + Hindi language data (Stage 2 of extraction pipeline) # System deps: Tesseract OCR (Stage 2 of extraction pipeline — CPU-only, no GPU)
# tesseract-ocr: ~50MB — CPU-only, no GPU needed # eng: English, hin: Hindi — for bilingual Indian documents (Aadhaar, PAN, etc.)
# tesseract-ocr-hin: Hindi language pack for bilingual Indian documents (Aadhaar, PAN, etc.)
RUN apt-get update && apt-get install -y --no-install-recommends \ RUN apt-get update && apt-get install -y --no-install-recommends \
tesseract-ocr \ tesseract-ocr \
tesseract-ocr-eng \ tesseract-ocr-eng \
@@ -16,21 +15,22 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
libgl1 \ libgl1 \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
# Install Python dependencies (plain UTF-8 requirements.txt)
COPY services/api/requirements.txt /tmp/requirements.txt COPY services/api/requirements.txt /tmp/requirements.txt
RUN python - <<'PY' RUN pip install --upgrade pip && pip install -r /tmp/requirements.txt
from pathlib import Path
src = Path('/tmp/requirements.txt')
text = src.read_text(encoding='utf-16')
Path('/tmp/requirements-utf8.txt').write_text(text, encoding='utf-8')
PY
RUN pip install --upgrade pip && pip install -r /tmp/requirements-utf8.txt
# Copy app source
COPY . /app COPY . /app
WORKDIR /app/services/api WORKDIR /app/services/api
EXPOSE 8000 EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4", "--proxy-headers"] # --forwarded-allow-ips=* trusts X-Forwarded-For from nginx container
# Required so rate limiter and audit logs see real client IPs (not nginx's internal IP)
CMD ["uvicorn", "app.main:app", \
"--host", "0.0.0.0", \
"--port", "8000", \
"--workers", "4", \
"--proxy-headers", \
"--forwarded-allow-ips=*"]
Binary file not shown.