alexp97 commited on
Commit
e079c75
·
1 Parent(s): 8ad34ee

feat(docker): soporte para despliegue desacoplado multi-contenedor (local, nube o mixto)

Browse files
Dockerfile.backend ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =====================================================================================
2
+ # Dockerfile.backend — Imagen exclusiva para el backend FastAPI de AgroVisión.
3
+ #
4
+ # No compila ni incluye frontend. Puede desplegarse en:
5
+ # - Docker Compose local (servicio backend)
6
+ # - Servicios en la nube: Render, Fly.io, Cloud Run, AWS ECS, etc.
7
+ # =====================================================================================
8
+ FROM ghcr.io/astral-sh/uv:python3.13-bookworm-slim
9
+
10
+ # Dependencias de sistema mínimas para OpenCV y OnnxRuntime
11
+ RUN apt-get update \
12
+ && apt-get install -y --no-install-recommends libglib2.0-0 libgomp1 libxcb1 libgl1 \
13
+ && rm -rf /var/lib/apt/lists/*
14
+
15
+ # Usuario no-root (UID 1000)
16
+ RUN useradd -m -u 1000 user
17
+ ENV HOME=/home/user \
18
+ PATH=/home/user/app/.venv/bin:$PATH \
19
+ UV_PROJECT_ENVIRONMENT=/home/user/app/.venv \
20
+ UV_LINK_MODE=copy \
21
+ UV_COMPILE_BYTECODE=1 \
22
+ PYTHONUNBUFFERED=1 \
23
+ COUNTING_ENABLED=false \
24
+ EVENTS_PERSIST=false
25
+
26
+ USER user
27
+ WORKDIR /home/user/app
28
+
29
+ # Dependencias Python
30
+ COPY --chown=user pyproject.toml uv.lock ./
31
+ RUN uv sync --no-dev --frozen --no-cache
32
+
33
+ # Código de la aplicación backend
34
+ COPY --chown=user backend/ ./backend/
35
+
36
+ EXPOSE 8000
37
+ CMD ["uvicorn", "backend.main:app", "--host", "0.0.0.0", "--port", "8000"]
Dockerfile.frontend ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =====================================================================================
2
+ # Dockerfile.frontend — Imagen exclusiva para el frontend Astro de AgroVisión.
3
+ #
4
+ # Multi-stage:
5
+ # (1) Compila Astro con pnpm
6
+ # (2) Nginx Alpine ultra-ligero con proxy reverso dinámico hacia el backend
7
+ #
8
+ # Uso:
9
+ # - Local: Se conecta al contenedor 'backend:8000'
10
+ # - Nube: BACKEND_URL=https://tu-backend.onrender.com
11
+ # =====================================================================================
12
+
13
+ # --- Stage 1: Build de la UI Astro ---
14
+ FROM node:22-bookworm-slim AS builder
15
+ WORKDIR /ui
16
+ RUN corepack enable
17
+
18
+ COPY frontend/package.json frontend/pnpm-lock.yaml frontend/pnpm-workspace.yaml ./
19
+ RUN pnpm install --frozen-lockfile
20
+
21
+ COPY frontend/ ./
22
+ ARG PUBLIC_API_URL=""
23
+ ENV PUBLIC_API_URL=$PUBLIC_API_URL
24
+ RUN pnpm build
25
+
26
+ # --- Stage 2: Nginx para servir el frontend estático ---
27
+ FROM nginx:1.27-alpine
28
+
29
+ # Plantilla de Nginx procesada automáticamente por envsubst en el arranque
30
+ COPY docker/nginx.conf.template /etc/nginx/templates/default.conf.template
31
+
32
+ # Copiar el build generado
33
+ COPY --from=builder /ui/dist /usr/share/nginx/html
34
+
35
+ # URL por defecto hacia el servicio backend (sobrescribible con -e BACKEND_URL=...)
36
+ ENV BACKEND_URL=http://backend:8000
37
+
38
+ EXPOSE 80
39
+ CMD ["nginx", "-g", "daemon off;"]
docker-compose.split.yml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =====================================================================================
2
+ # AgroVisión — Despliegue Desacoplado (Front y Back en contenedores independientes)
3
+ #
4
+ # Uso:
5
+ # docker compose -f docker-compose.split.yml up --build
6
+ #
7
+ # Modos posibles:
8
+ # 1. Todo en Local:
9
+ # - Backend en http://localhost:8000
10
+ # - Frontend en http://localhost:3000
11
+ # 2. Frontend Local conectándose a Backend en la Nube:
12
+ # - Cambia en 'frontend' -> BACKEND_URL=https://tu-backend-en-nube.com
13
+ # =====================================================================================
14
+ services:
15
+ backend:
16
+ build:
17
+ context: .
18
+ dockerfile: Dockerfile.backend
19
+ container_name: agrovision-backend
20
+ ports:
21
+ - "8000:8000"
22
+ env_file:
23
+ - .env
24
+ environment:
25
+ - APP_ENV=development
26
+ - COUNTING_ENABLED=false
27
+ - RATE_LIMIT_PER_MIN=120
28
+ healthcheck:
29
+ test: ["CMD-SHELL", "python -c \"import urllib.request; urllib.request.urlopen('http://localhost:8000/api/status')\""]
30
+ interval: 15s
31
+ timeout: 5s
32
+ retries: 5
33
+
34
+ frontend:
35
+ build:
36
+ context: .
37
+ dockerfile: Dockerfile.frontend
38
+ container_name: agrovision-frontend
39
+ ports:
40
+ - "3000:80"
41
+ environment:
42
+ # URL a la que Nginx redirige las llamadas /api/
43
+ - BACKEND_URL=http://backend:8000
44
+ depends_on:
45
+ backend:
46
+ condition: service_healthy
docker/nginx.conf.template ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ server {
2
+ listen 80;
3
+ server_name localhost;
4
+
5
+ root /usr/share/nginx/html;
6
+ index index.html;
7
+
8
+ # Compresión gzip para assets web
9
+ gzip on;
10
+ gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
11
+
12
+ # Frontend estático con soporte para rutas SPA
13
+ location / {
14
+ try_files $uri $uri/ /index.html;
15
+ }
16
+
17
+ # Proxy inverso para las llamadas de /api/ hacia el backend (local en docker o nube)
18
+ location /api/ {
19
+ proxy_pass ${BACKEND_URL}/api/;
20
+ proxy_http_version 1.1;
21
+ proxy_set_header Upgrade $http_upgrade;
22
+ proxy_set_header Connection 'upgrade';
23
+ proxy_set_header Host $host;
24
+ proxy_cache_bypass $http_upgrade;
25
+ proxy_set_header X-Real-IP $remote_addr;
26
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
27
+ proxy_set_header X-Forwarded-Proto $scheme;
28
+ }
29
+ }
docs/ejecucion.md CHANGED
@@ -156,11 +156,32 @@ Reinicia el backend, ve a la pestaña **Conteo** (verás *"(datos de prueba / mo
156
  El MVP no requiere transpilación. Como alternativa al arranque con `uv`, hay imágenes Docker:
157
 
158
  ```bash
159
- docker compose up --build # gateway en :8000 (sirve API + UI Astro compilada)
160
  ```
161
 
162
  > Para activar el conteo real en la imagen, descomenta el bloque `hf_hub_download` en el `Dockerfile` (raíz) y pon `COUNTING_ENABLED=true`, `MODEL_BACKEND=onnx`.
163
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  ---
165
 
166
  ## 5. Despliegue en Producción / Cloud
 
156
  El MVP no requiere transpilación. Como alternativa al arranque con `uv`, hay imágenes Docker:
157
 
158
  ```bash
159
+ docker compose up --build # gateway en :8000 (sirve API + UI Astro compilada en 1 solo contenedor)
160
  ```
161
 
162
  > Para activar el conteo real en la imagen, descomenta el bloque `hf_hub_download` en el `Dockerfile` (raíz) y pon `COUNTING_ENABLED=true`, `MODEL_BACKEND=onnx`.
163
 
164
+ ### 4.1 Despliegue Desacoplado / Multi-Contenedor (Front y Back Separados)
165
+
166
+ Si deseas desacoplar la interfaz y el servidor (para correr todo en local por separado, o conectar un Frontend local con un Backend en la nube):
167
+
168
+ ```bash
169
+ docker compose -f docker-compose.split.yml up --build -d
170
+ ```
171
+
172
+ - **Frontend (Nginx + Astro estático)**: `http://localhost:3000/`
173
+ - **Backend (FastAPI)**: `http://localhost:8000/`
174
+
175
+ **Modo Mixto (Frontend local -> Backend en la nube):**
176
+ En `docker-compose.split.yml`, cambia la variable `BACKEND_URL` del servicio frontend por tu URL en la nube:
177
+ ```yaml
178
+ services:
179
+ frontend:
180
+ environment:
181
+ - BACKEND_URL=https://tu-backend.onrender.com
182
+ ```
183
+ Nginx redirigirá internamente las llamadas `/api/*` hacia tu backend en la nube, evitando problemas de CORS en el navegador.
184
+
185
  ---
186
 
187
  ## 5. Despliegue en Producción / Cloud
frontend/src/pages/index.astro CHANGED
@@ -1,5 +1,6 @@
1
  ---
2
  import "../styles/global.css";
 
3
  ---
4
 
5
  <!doctype html>
@@ -909,7 +910,17 @@ import "../styles/global.css";
909
  <script is:inline src="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.js"></script>
910
  <script is:inline src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
911
 
 
 
 
 
 
912
  <script is:inline>
 
 
 
 
 
913
  // ===== Estado EFÍMERO (solo memoria; se borra al refrescar) =====
914
  let creds = {};
915
  let parcels = [];
@@ -960,7 +971,7 @@ import "../styles/global.css";
960
  dot.className = "relative inline-flex rounded-full h-2 w-2 bg-red-500";
961
  return;
962
  }
963
- fetch("./api/credentials/status")
964
  .then((r) => r.ok ? r.json() : null)
965
  .then((s) => {
966
  if (!s) {
@@ -993,7 +1004,7 @@ import "../styles/global.css";
993
  // ===== Telemetría (Fase 9) =====
994
  function track(action, meta = {}) {
995
  try {
996
- fetch("./api/events", {
997
  method: "POST",
998
  headers: { "Content-Type": "application/json" },
999
  body: JSON.stringify({ action, meta, session_id: sessionId, ts: new Date().toISOString() }),
@@ -1007,7 +1018,7 @@ import "../styles/global.css";
1007
 
1008
  async function api(path, opts = {}) {
1009
  try {
1010
- const res = await fetch("./api" + path, {
1011
  ...opts,
1012
  headers: { ...(opts.body ? { "Content-Type": "application/json" } : {}), ...authHeaders(), ...(opts.headers || {}) },
1013
  });
@@ -2930,7 +2941,7 @@ import "../styles/global.css";
2930
  });
2931
  $("btn-check-env").addEventListener("click", async () => {
2932
  try {
2933
- const r = await fetch("./api/credentials/status");
2934
  if (!r.ok) return notify("No disponible", "No se pudo consultar el .env del servidor.");
2935
  const s = await r.json();
2936
  appEnv = s.env || "development";
@@ -3056,7 +3067,7 @@ import "../styles/global.css";
3056
  let sbUrl = creds.sbUrl;
3057
  if (!sbUrl) {
3058
  try {
3059
- const r = await fetch("./api/credentials/status");
3060
  if (r.ok) {
3061
  const s = await r.json();
3062
  if (s.supabase_url) sbUrl = s.supabase_url;
@@ -3072,7 +3083,7 @@ import "../styles/global.css";
3072
  try {
3073
  fingerprint = await sha256(sbUrl);
3074
  track("profile_connect_attempt", { hash: fingerprint });
3075
- const r = await fetch("./api/profiles/connect", {
3076
  method: "POST",
3077
  headers: { "Content-Type": "application/json" },
3078
  body: JSON.stringify({ supabase_url_hash: fingerprint, display_name: $("settings-display-name").value || "Agrónomo" })
@@ -3118,7 +3129,7 @@ import "../styles/global.css";
3118
  $("btn-telemetry").style.display = "none";
3119
 
3120
  try {
3121
- const r = await fetch(`./api/profiles/${id}`);
3122
  if (r.ok) {
3123
  currentProfile = await r.json();
3124
  updateProfileUI();
@@ -3170,7 +3181,7 @@ import "../styles/global.css";
3170
 
3171
  async function checkMissingCredentials() {
3172
  try {
3173
- const r = await fetch("./api/credentials/status");
3174
  if (!r.ok) return;
3175
  const s = await r.json();
3176
  appEnv = s.env || "development";
@@ -3237,14 +3248,14 @@ import "../styles/global.css";
3237
  const sharedProfileId = hashParams.get("profile");
3238
 
3239
  try {
3240
- const r = await fetch("./api/status");
3241
  backendOk = r.ok;
3242
  $("db-status-text").innerText = backendOk ? "Backend conectado" : "Backend no disponible";
3243
  if (backendOk) { $("db-status-text").classList.replace("text-stone-400", "text-emerald-400"); }
3244
  } catch { $("db-status-text").innerText = "Backend no disponible"; }
3245
 
3246
  try {
3247
- const r = await fetch("./api/credentials/status");
3248
  if (r.ok) {
3249
  const s = await r.json();
3250
  appEnv = s.env || "development";
@@ -3261,7 +3272,7 @@ import "../styles/global.css";
3261
  const savedProfileId = localStorage.getItem("agrovision_profile_id");
3262
  if (savedProfileId) {
3263
  try {
3264
- const r = await fetch(`./api/profiles/${savedProfileId}`);
3265
  if (r.ok) {
3266
  currentProfile = await r.json();
3267
  profileId = currentProfile.id;
 
1
  ---
2
  import "../styles/global.css";
3
+ const publicApiUrl = import.meta.env.PUBLIC_API_URL || "";
4
  ---
5
 
6
  <!doctype html>
 
910
  <script is:inline src="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.js"></script>
911
  <script is:inline src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
912
 
913
+ <!-- Base URL de Backend para despliegue desacoplado/nube -->
914
+ <script is:inline define:vars={{ publicApiUrl }}>
915
+ window.AGROVISION_API_URL = window.AGROVISION_API_URL || publicApiUrl || "";
916
+ </script>
917
+
918
  <script is:inline>
919
+ function apiUrl(path) {
920
+ const base = (window.AGROVISION_API_URL || "").replace(/\/$/, "");
921
+ const p = path.startsWith("/") ? path : `/${path}`;
922
+ return base ? `${base}/api${p}` : `./api${p}`;
923
+ }
924
  // ===== Estado EFÍMERO (solo memoria; se borra al refrescar) =====
925
  let creds = {};
926
  let parcels = [];
 
971
  dot.className = "relative inline-flex rounded-full h-2 w-2 bg-red-500";
972
  return;
973
  }
974
+ fetch(apiUrl("/credentials/status"))
975
  .then((r) => r.ok ? r.json() : null)
976
  .then((s) => {
977
  if (!s) {
 
1004
  // ===== Telemetría (Fase 9) =====
1005
  function track(action, meta = {}) {
1006
  try {
1007
+ fetch(apiUrl("/events"), {
1008
  method: "POST",
1009
  headers: { "Content-Type": "application/json" },
1010
  body: JSON.stringify({ action, meta, session_id: sessionId, ts: new Date().toISOString() }),
 
1018
 
1019
  async function api(path, opts = {}) {
1020
  try {
1021
+ const res = await fetch(apiUrl(path), {
1022
  ...opts,
1023
  headers: { ...(opts.body ? { "Content-Type": "application/json" } : {}), ...authHeaders(), ...(opts.headers || {}) },
1024
  });
 
2941
  });
2942
  $("btn-check-env").addEventListener("click", async () => {
2943
  try {
2944
+ const r = await fetch(apiUrl("/credentials/status"));
2945
  if (!r.ok) return notify("No disponible", "No se pudo consultar el .env del servidor.");
2946
  const s = await r.json();
2947
  appEnv = s.env || "development";
 
3067
  let sbUrl = creds.sbUrl;
3068
  if (!sbUrl) {
3069
  try {
3070
+ const r = await fetch(apiUrl("/credentials/status"));
3071
  if (r.ok) {
3072
  const s = await r.json();
3073
  if (s.supabase_url) sbUrl = s.supabase_url;
 
3083
  try {
3084
  fingerprint = await sha256(sbUrl);
3085
  track("profile_connect_attempt", { hash: fingerprint });
3086
+ const r = await fetch(apiUrl("/profiles/connect"), {
3087
  method: "POST",
3088
  headers: { "Content-Type": "application/json" },
3089
  body: JSON.stringify({ supabase_url_hash: fingerprint, display_name: $("settings-display-name").value || "Agrónomo" })
 
3129
  $("btn-telemetry").style.display = "none";
3130
 
3131
  try {
3132
+ const r = await fetch(apiUrl(`/profiles/${id}`));
3133
  if (r.ok) {
3134
  currentProfile = await r.json();
3135
  updateProfileUI();
 
3181
 
3182
  async function checkMissingCredentials() {
3183
  try {
3184
+ const r = await fetch(apiUrl("/credentials/status"));
3185
  if (!r.ok) return;
3186
  const s = await r.json();
3187
  appEnv = s.env || "development";
 
3248
  const sharedProfileId = hashParams.get("profile");
3249
 
3250
  try {
3251
+ const r = await fetch(apiUrl("/status"));
3252
  backendOk = r.ok;
3253
  $("db-status-text").innerText = backendOk ? "Backend conectado" : "Backend no disponible";
3254
  if (backendOk) { $("db-status-text").classList.replace("text-stone-400", "text-emerald-400"); }
3255
  } catch { $("db-status-text").innerText = "Backend no disponible"; }
3256
 
3257
  try {
3258
+ const r = await fetch(apiUrl("/credentials/status"));
3259
  if (r.ok) {
3260
  const s = await r.json();
3261
  appEnv = s.env || "development";
 
3272
  const savedProfileId = localStorage.getItem("agrovision_profile_id");
3273
  if (savedProfileId) {
3274
  try {
3275
+ const r = await fetch(apiUrl(`/profiles/${savedProfileId}`));
3276
  if (r.ok) {
3277
  currentProfile = await r.json();
3278
  profileId = currentProfile.id;