chore(deploy): Dockerfile + compose + entrypoint para Coolify (Paso 5)
QUÉ
Empaqueta el backend para desplegar en Coolify (VPS). El motor sigue
arrancando MANUAL (botón); aquí solo se containeriza y se automatiza el
arranque reproducible. Postgres NO va en el compose: lo gestiona Coolify y
provee DATABASE_URL.
ARCHIVOS
- Dockerfile: python:3.11-slim, imagen ligera (sin libreoffice/fonts; este
backend no genera documentos). Deps de sistema mínimas: postgresql-client
(psql/pg_isready para el entrypoint) y curl (healthcheck). Caché de capas
(requirements antes del código). EXPOSE 8003. HEALTHCHECK a /health.
CMD uvicorn app.main:app --host 0.0.0.0 --port 8003 (un solo worker: el
motor es un singleton en proceso con tarea asyncio + conexión persistente).
- entrypoint.sh: exige DATABASE_URL, espera a Postgres (pg_isready, ~60s máx),
aplica db/schema.sql (idempotente: IF NOT EXISTS / CREATE OR REPLACE) y hace
exec del CMD (uvicorn como PID 1, señales limpias). Sin paso manual de schema.
- docker-compose.yml: un servicio, stateless (sin volúmenes), restart
unless-stopped, env vars con defaults; Postgres externo via DATABASE_URL.
- .dockerignore: imagen lean; excluye .env (secretos), .venv, demo-sheets y
docs. Conserva .env.example (doc, sin secretos) y db/schema.sql (lo necesita
el entrypoint).
- app/main.py: nuevo GET /health liviano que NO toca la DB (liveness para el
HEALTHCHECK).
ENV QUE ESPERA DE COOLIFY
DATABASE_URL (obligatoria, formato postgresql://... SIN +psycopg; el db.py usa
psycopg crudo), ESPEJO_TOKEN (sin ella /espejo da 503 fail-closed), TZ (opcional,
default America/Mexico_City), EVOLUTION_API_* (placeholders, aún no usadas).
EVIDENCIA (build + corrida en caliente, Docker local + Postgres efímero)
- Build OK; imagen 427MB (sin libreoffice). Dentro: db/schema.sql y .env.example
presentes; .env, demo-sheets y .venv excluidos; psql/pg_isready/curl/python3.11.
- Entrypoint en caliente: esperó a Postgres, aplicó el schema (7 tablas, 6
índices, 1 vista) y arrancó uvicorn en 0.0.0.0:8003.
- /health -> 200 {"status":"ok"}; HEALTHCHECK de Docker reporta "healthy".
- /engine/status -> running=False (motor manual, sin autostart), db_ok=True.
- DB-independiente: con Postgres DETENIDO, /health sigue 200, mientras
/engine/status db_ok=False y /live -> 503. Confirma que /health no toca la DB.
This commit is contained in:
1 parent
1028b8e9fe
commit
340e7e2352
5 files changed
+114
No files matched your search
@@ -0,0 +1,29 @@
|
||||
# Control de versiones y entorno local
|
||||
.git
|
||||
.gitignore
|
||||
.venv
|
||||
venv
|
||||
|
||||
# Bytecode
|
||||
__pycache__
|
||||
*.pyc
|
||||
*.pyo
|
||||
|
||||
# Secretos (el .env real NO entra). Se conserva .env.example (doc, sin secretos).
|
||||
.env
|
||||
.env.local
|
||||
|
||||
# DBs locales / sueltas
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
*.db
|
||||
|
||||
# Editores / SO
|
||||
.DS_Store
|
||||
.idea
|
||||
.vscode
|
||||
|
||||
# Demo desechable y docs internas (no se necesitan en runtime)
|
||||
demo-sheets
|
||||
README.md
|
||||
CLAUDE.md
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
PIP_NO_CACHE_DIR=1 \
|
||||
PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
||||
TZ=America/Mexico_City
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Deps de sistema MÍNIMAS:
|
||||
# - postgresql-client: psql + pg_isready para el entrypoint (esperar DB, aplicar schema).
|
||||
# - curl: para el HEALTHCHECK.
|
||||
# (Sin libreoffice/fonts: este backend no genera documentos.)
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends postgresql-client curl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Deps de Python primero (aprovecha la caché de capas).
|
||||
COPY requirements.txt .
|
||||
RUN pip install -r requirements.txt
|
||||
|
||||
# Resto del código.
|
||||
COPY . .
|
||||
RUN chmod +x /app/entrypoint.sh
|
||||
|
||||
EXPOSE 8003
|
||||
|
||||
# Healthcheck nativo de Docker — Coolify lo reutiliza. Pega a /health (no toca DB).
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=40s --retries=3 \
|
||||
CMD curl -fsS http://localhost:8003/health || exit 1
|
||||
|
||||
# El entrypoint aplica el schema (idempotente) y luego hace exec del CMD.
|
||||
ENTRYPOINT ["/app/entrypoint.sh"]
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8003"]
|
||||
@@ -25,6 +25,13 @@ from engine.runner import runner
|
||||
app = FastAPI(title="Collina — Motor generativo", version="0.1")
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
async def health():
|
||||
"""Liveness liviano para el HEALTHCHECK de Docker/Coolify. NO toca la DB:
|
||||
solo confirma que el proceso de la app responde."""
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.post("/engine/start")
|
||||
async def engine_start():
|
||||
return await runner.start()
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
services:
|
||||
cash-monitor:
|
||||
build: .
|
||||
container_name: cash-monitor
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "8003:8003"
|
||||
environment:
|
||||
- DATABASE_URL=${DATABASE_URL} # lo provee Coolify (Postgres gestionado)
|
||||
- ESPEJO_TOKEN=${ESPEJO_TOKEN}
|
||||
- TZ=${TZ:-America/Mexico_City}
|
||||
# Evolution API — fases posteriores; placeholders, el código aún no los usa.
|
||||
- EVOLUTION_API_URL=${EVOLUTION_API_URL:-}
|
||||
- EVOLUTION_API_KEY=${EVOLUTION_API_KEY:-}
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/bin/sh
|
||||
# Entrypoint del backend Collina.
|
||||
# 1) Verifica DATABASE_URL. 2) Espera a que Postgres responda.
|
||||
# 3) Aplica db/schema.sql (idempotente: IF NOT EXISTS / CREATE OR REPLACE VIEW).
|
||||
# 4) exec del CMD (uvicorn) -> queda como PID 1 para manejar señales limpio.
|
||||
set -e
|
||||
|
||||
if [ -z "$DATABASE_URL" ]; then
|
||||
echo "[entrypoint] ERROR: DATABASE_URL no está definido." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[entrypoint] Esperando a PostgreSQL..."
|
||||
i=0
|
||||
until pg_isready -d "$DATABASE_URL" >/dev/null 2>&1; do
|
||||
i=$((i+1))
|
||||
if [ "$i" -ge 30 ]; then
|
||||
echo "[entrypoint] ERROR: PostgreSQL no respondió tras ~60s." >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
echo "[entrypoint] PostgreSQL responde."
|
||||
|
||||
echo "[entrypoint] Aplicando esquema (idempotente)..."
|
||||
psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f db/schema.sql
|
||||
echo "[entrypoint] Esquema aplicado. Arrancando app..."
|
||||
|
||||
exec "$@"
|
||||
Reference in new issue
Block a user