Saltar a contenido

05 — Deploy a producción

Asume que terminaste 04-instalacion.md y Django arranca con runserver.

Arquitectura final del deployment

[ Internet ]
     │ HTTPS (443)
[ nginx ]
  ├── /static/*  → /home/blimxapp/saas/chatbot-v3-workspace/static/  (filesystem)
  ├── /media/*   → /home/blimxapp/saas/chatbot-v3-workspace/backend_django/media/
  ├── /v3/*      → http://127.0.0.1:8000  (Django)
  ├── /api/*     → http://127.0.0.1:8000  (Django)
  ├── /admin/*   → http://127.0.0.1:8000  (Django admin)
  └── /          → /home/blimxapp/saas/chatbot-v3-workspace/apps/dashboard/dist/  (SPA)
                       fallback → /index.html para react-router
     │ proxy_pass
[ gunicorn :8000 ]    ← gestionado por systemd (blimx-django.service)
   ├── 5 workers
   └── 2 threads c/u

1. Crear systemd unit de Django

Copia el template de .saas-docs/infra/blimx-django.service.example a /etc/systemd/system/blimx-django.service y ajusta los paths/usuario:

sudo cp .saas-docs/infra/blimx-django.service.example /etc/systemd/system/blimx-django.service
sudo nano /etc/systemd/system/blimx-django.service

Lo que debes editar del template:

  • User=blimxapp → tu usuario
  • WorkingDirectory=/home/blimxapp/saas/chatbot-v3-workspace/backend_django
  • EnvironmentFile= → opcional; se lee del .env automáticamente vía python-dotenv
  • ExecStart= → ajusta el path al venv/bin/gunicorn

Ver infra/blimx-django.service.example para el contenido completo.

2. Habilitar y arrancar el servicio

sudo systemctl daemon-reload
sudo systemctl enable --now blimx-django
sudo systemctl status blimx-django

Debe estar active (running). Si no, ver logs:

sudo journalctl -u blimx-django -f --since '5 minutes ago'

3. Verificar que Django responde en :8000

curl http://127.0.0.1:8000/health
# {"status": "ok", "db": true}

4. Configurar nginx

Ver doc dedicado 06-nginx.md. Resumen rápido:

sudo cp .saas-docs/infra/nginx-superbot.conf.example /etc/nginx/sites-available/blimx
sudo nano /etc/nginx/sites-available/blimx
# edita server_name, paths del root, paths de SSL
sudo ln -s /etc/nginx/sites-available/blimx /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

5. Permisos para que nginx lea los estáticos

El usuario nginx (o www-data según distro) debe poder atravesar el path hasta los estáticos. La forma más limpia:

# Identifica como qué usuario corre nginx
ps -eo user,comm | grep nginx | grep -v grep | head -1
# Suele ser "nginx" en RHEL/Plesk, "www-data" en Debian/Ubuntu

# Añade ese usuario al grupo del usuario de la app
sudo usermod -a -G blimxapp nginx     # (o www-data)
sudo systemctl restart nginx          # NO reload — restart para aplicar grupos

Verifica que /home/blimxapp tiene permisos 750 (drwxr-x---) y el grupo es blimxapp. Si no:

sudo chmod 750 /home/blimxapp

6. Configurar HTTPS

Si usas Let's Encrypt sin Plesk:

sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d app.tudominio.com -d widget.tudominio.com
# certbot edita el vhost para añadir SSL automáticamente

Plesk: marca el checkbox de Let's Encrypt en el dominio.

7. Configurar webhook Stripe

  1. Ve a https://dashboard.stripe.com/webhooks → Add endpoint.
  2. URL: https://app.tudominio.com/api/billing/stripe/webhook/
  3. Eventos a escuchar:
  4. checkout.session.completed
  5. customer.subscription.created
  6. customer.subscription.updated
  7. customer.subscription.deleted
  8. invoice.payment_succeeded
  9. invoice.payment_failed
  10. Copia el Signing secret (whsec_...) en .env como STRIPE_WEBHOOK_SECRET.
  11. Reinicia Django: sudo systemctl restart blimx-django.

8. Smoke test final end-to-end

# Endpoints públicos del widget
curl -sI https://widget.tudominio.com/v3/health
curl -sI https://widget.tudominio.com/static/v3/blimx-v3-chatbot-loader.js

# API del dashboard
curl -sI https://app.tudominio.com/api/health/
curl -sI https://app.tudominio.com/         # debe devolver el index.html del dashboard

# Stripe webhook (Stripe lo prueba desde su panel: "Send test webhook")

Si todos responden 200 o 301→200, el SaaS está deployado.

Operación diaria

Acción Comando
Reiniciar Django sudo systemctl restart blimx-django
Ver logs sudo journalctl -u blimx-django -f
Ver estado sudo systemctl status blimx-django
Recargar nginx (config) sudo systemctl reload nginx
Reiniciar nginx (full) sudo systemctl restart nginx
Aplicar nuevas migraciones cd backend_django && source venv/bin/activate && python manage.py migrate && sudo systemctl restart blimx-django
Build nuevo del dashboard cd apps/dashboard && npm run build
Build nuevo del widget cd static/v3 && node build.js

Actualizar el código (deploy de nueva versión)

cd /home/blimxapp/saas/chatbot-v3-workspace
git pull   # o subir un nuevo zip y reemplazar archivos

# Backend
cd backend_django && source venv/bin/activate
pip install -r requirements.txt    # si hay deps nuevas
python manage.py migrate
python manage.py collectstatic --noinput

# Dashboard
cd ../apps/dashboard && npm install && npm run build

# Superadmin
cd ../superadmin && npm install && npm run build

# Widget
cd ../../static/v3 && npm install && node build.js

# Restart
sudo systemctl restart blimx-django
sudo systemctl reload nginx

Tiempo total: <2 minutos.