Dashboard-Automatizase/README-DEPLOY.md
Luis 2015b130d0 feat: add Dockerfile and Kubernetes manifests for deployment
- Create multi-stage Dockerfile with node:20-alpine
- Add .dockerignore for optimized build context
- Create Kubernetes manifests (deployment, service, ingress, secret)
- Add health check endpoint at /api/health
- Configure next.config.ts with standalone output
- Add comprehensive deployment documentation in README-DEPLOY.md

Story: 4.1 - Criar Dockerfile e Manifests Kubernetes para Deploy

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-12 19:57:26 -03:00

13 KiB

🚀 Guia de Deploy - AutomatizaSE Portal

Este documento contém instruções completas para build, deploy e gerenciamento da aplicação AutomatizaSE Portal no Kubernetes.


📋 Pré-requisitos

Antes de iniciar o deploy, certifique-se de ter:

  • Docker instalado (v24+)
  • kubectl instalado e configurado
  • Acesso ao cluster Kubernetes (v1.28+)
  • Acesso ao registry de imagens (Docker Hub, GCR, ou registry privado)
  • Nginx Ingress Controller instalado no cluster
  • (Opcional) cert-manager instalado para certificados automáticos Let's Encrypt

🏗️ Seção 1: Build da Imagem Docker

1.1 Build Local

# Build da imagem com tag versionada
docker build -t registry.automatizase.com/portal:v1.0.0 .

# Verificar imagem criada
docker images | grep portal

1.2 Tag Latest

# Criar tag 'latest' para facilitar referência
docker tag registry.automatizase.com/portal:v1.0.0 registry.automatizase.com/portal:latest

1.3 Push para Registry

Opção A: Docker Hub

# Login
docker login

# Push
docker tag registry.automatizase.com/portal:v1.0.0 docker.io/automatizase/portal:v1.0.0
docker push docker.io/automatizase/portal:v1.0.0

Opção B: Registry Privado

# Login
docker login registry.automatizase.com

# Push
docker push registry.automatizase.com/portal:v1.0.0
docker push registry.automatizase.com/portal:latest

Opção C: Google Container Registry (GCR)

# Configure gcloud auth
gcloud auth configure-docker

# Tag e push
docker tag registry.automatizase.com/portal:v1.0.0 gcr.io/seu-projeto/portal:v1.0.0
docker push gcr.io/seu-projeto/portal:v1.0.0

⚠️ IMPORTANTE: Ajuste o caminho da imagem em k8s/deployment.yaml conforme o registry utilizado.


🔐 Seção 2: Criar Secret no Cluster

O Secret contém todas as variáveis de ambiente sensíveis da aplicação.

2.1 Criar Secret via kubectl

kubectl create secret generic portal-secrets \
  --from-literal=NEXT_PUBLIC_SITE_URL=https://portal.automatizase.com.br \
  --from-literal=NEXT_PUBLIC_SUPABASE_URL=https://supabase.automatizase.com.br \
  --from-literal=NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... \
  --from-literal=SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... \
  --from-literal=EVOLUTION_API_URL=https://evolutionapi.automatizase.com.br \
  --from-literal=EVOLUTION_API_KEY=03919932dcb10fee6f28b1f1013b304c \
  --from-literal=EVOLUTION_INSTANCE_NAMES=Rita,Lucia\ Refugio \
  --from-literal=N8N_OAUTH_URL=https://n8n.automatizase.com.br/webhook/google-oauth \
  --from-literal=N8N_API_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... \
  --from-literal=N8N_API_URL=https://n8n.automatizase.com.br/api/v1 \
  --from-literal=NEXT_PUBLIC_GOOGLE_CLIENT_ID=174466774807-tdsht53agf7v40suk5mmqgmfrn4iskck.apps.googleusercontent.com \
  --from-literal=GOOGLE_CLIENT_SECRET=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 \
  -n automatizase

2.2 Criar Secret via Arquivo (Alternativa)

# Copiar arquivo template
cp k8s/secret.yaml k8s/secret-production.yaml

# Editar secret-production.yaml com valores reais
# NUNCA commitar secret-production.yaml!

# Aplicar
kubectl apply -f k8s/secret-production.yaml

2.3 Verificar Secret Criado

kubectl get secret portal-secrets -n automatizase
kubectl describe secret portal-secrets -n automatizase

⚠️ SEGURANÇA: NUNCA commite valores reais de secrets no Git! Use variáveis de CI/CD ou gerenciadores de secrets (Sealed Secrets, External Secrets Operator, etc.)


🚀 Seção 3: Deploy dos Manifests Kubernetes

3.1 Deploy Ordenado (Recomendado)

# 1. Criar namespace
kubectl apply -f k8s/namespace.yaml

# 2. Criar secret (se ainda não criou no passo anterior)
kubectl create secret generic portal-secrets ... # (ver Seção 2)

# 3. Deploy da aplicação
kubectl apply -f k8s/deployment.yaml

# 4. Criar service
kubectl apply -f k8s/service.yaml

# 5. Criar ingress
kubectl apply -f k8s/ingress.yaml

3.2 Deploy Rápido (Todos de Uma Vez)

# Aplicar todos os manifests (exceto secret)
kubectl apply -f k8s/namespace.yaml
kubectl apply -f k8s/deployment.yaml
kubectl apply -f k8s/service.yaml
kubectl apply -f k8s/ingress.yaml

3.3 Deploy com Kustomize (Futuro)

# Se configurado com kustomize
kubectl apply -k k8s/

Seção 4: Verificação do Deploy

4.1 Verificar Pods

# Listar pods
kubectl get pods -n automatizase

# Verificar status detalhado
kubectl describe pod <pod-name> -n automatizase

# Ver logs em tempo real
kubectl logs -f deployment/portal -n automatizase

# Ver logs de todos os pods
kubectl logs -f -l app=portal -n automatizase

4.2 Verificar Service

# Listar services
kubectl get svc -n automatizase

# Detalhes do service
kubectl describe svc portal-service -n automatizase

4.3 Verificar Ingress

# Listar ingress
kubectl get ingress -n automatizase

# Detalhes do ingress
kubectl describe ingress portal-ingress -n automatizase

# Verificar endereço IP alocado
kubectl get ingress portal-ingress -n automatizase -o jsonpath='{.status.loadBalancer.ingress[0].ip}'

4.4 Verificar DNS

# Testar resolução DNS
nslookup portal.automatizase.com.br

# Testar conectividade
curl -I https://portal.automatizase.com.br

# Testar health check
curl https://portal.automatizase.com.br/api/health

4.5 Verificar Certificado TLS

# Ver certificado
kubectl get certificate -n automatizase

# Detalhes do certificado (se usar cert-manager)
kubectl describe certificate portal-tls-cert -n automatizase

# Verificar via curl
curl -vI https://portal.automatizase.com.br 2>&1 | grep -i 'SSL\|TLS'

🔧 Seção 5: Troubleshooting

5.1 Pod Não Inicia

Sintomas: Pod em estado CrashLoopBackOff, Error, ou ImagePullBackOff

Diagnóstico:

# Ver eventos do pod
kubectl describe pod <pod-name> -n automatizase

# Ver logs do pod
kubectl logs <pod-name> -n automatizase

# Ver logs do container anterior (se pod reiniciou)
kubectl logs <pod-name> -n automatizase --previous

Possíveis Causas:

  • ImagePullBackOff: Imagem não existe ou falta autenticação no registry
  • CrashLoopBackOff: Aplicação falha ao iniciar (verificar logs)
  • Secrets faltando: Verificar se portal-secrets existe e está correto

5.2 Health Check Falhando

Sintomas: Pod em estado Running mas não passa em readiness

Diagnóstico:

# Verificar health check endpoint diretamente
kubectl port-forward deployment/portal 3100:3100 -n automatizase
curl http://localhost:3100/api/health

Possíveis Causas:

  • Endpoint /api/health não responde
  • Timeout muito curto nos probes
  • Aplicação demora muito para iniciar

Soluções:

# Aumentar initialDelaySeconds no deployment.yaml
# Editar e aplicar novamente
kubectl edit deployment portal -n automatizase

5.3 Ingress Não Responde

Sintomas: curl https://portal.automatizase.com.br não responde ou retorna 404/502

Diagnóstico:

# Verificar se Nginx Ingress Controller está rodando
kubectl get pods -n ingress-nginx

# Ver logs do Ingress Controller
kubectl logs -f -n ingress-nginx deployment/ingress-nginx-controller

# Testar service diretamente (bypass ingress)
kubectl port-forward svc/portal-service 8080:80 -n automatizase
curl http://localhost:8080

Possíveis Causas:

  • DNS não aponta para IP do LoadBalancer
  • Certificado TLS inválido ou faltando
  • Nginx Ingress Controller não instalado

Soluções:

# Verificar IP do LoadBalancer
kubectl get ingress portal-ingress -n automatizase

# Configurar DNS apontando para o IP retornado
# Ex: portal.automatizase.com.br -> 203.0.113.10

5.4 Certificado TLS Inválido

Sintomas: Navegador retorna erro SSL/TLS

Soluções:

Opção A: Usar cert-manager (Automático)

# Instalar cert-manager
kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.13.0/cert-manager.yaml

# Criar ClusterIssuer Let's Encrypt
cat <<EOF | kubectl apply -f -
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: letsencrypt-prod
spec:
  acme:
    server: https://acme-v02.api.letsencrypt.org/directory
    email: devops@automatizase.com.br
    privateKeySecretRef:
      name: letsencrypt-prod
    solvers:
    - http01:
        ingress:
          class: nginx
EOF

# Descomentar annotation em k8s/ingress.yaml
# cert-manager.io/cluster-issuer: letsencrypt-prod

# Reaplicar ingress
kubectl apply -f k8s/ingress.yaml

Opção B: Certificado Manual

# Criar secret com certificado existente
kubectl create secret tls portal-tls-cert \
  --cert=path/to/tls.crt \
  --key=path/to/tls.key \
  -n automatizase

🔄 Seção 6: Rollback

6.1 Rollback para Versão Anterior

# Ver histórico de deploys
kubectl rollout history deployment/portal -n automatizase

# Rollback para revisão anterior
kubectl rollout undo deployment/portal -n automatizase

# Rollback para revisão específica
kubectl rollout undo deployment/portal --to-revision=2 -n automatizase

6.2 Verificar Status do Rollback

# Acompanhar rollout
kubectl rollout status deployment/portal -n automatizase

🔄 Seção 7: Atualização (Novo Deploy)

7.1 Deploy Nova Versão

# 1. Build nova imagem com nova tag
docker build -t registry.automatizase.com/portal:v1.0.1 .
docker push registry.automatizase.com/portal:v1.0.1

# 2. Atualizar imagem no deployment
kubectl set image deployment/portal \
  nextjs=registry.automatizase.com/portal:v1.0.1 \
  -n automatizase

# 3. Acompanhar rollout
kubectl rollout status deployment/portal -n automatizase

7.2 Deploy com Zero Downtime

O Deployment já está configurado com estratégia RollingUpdate (padrão), garantindo zero downtime:

spec:
  replicas: 2  # Mínimo de 2 replicas para HA
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 0      # Nunca remover todos os pods
      maxSurge: 1            # Criar 1 pod extra durante update

7.3 Restart Deployment (Sem Trocar Imagem)

# Restart todos os pods (útil para recarregar secrets)
kubectl rollout restart deployment/portal -n automatizase

🔍 Seção 8: Monitoramento e Logs

8.1 Logs em Tempo Real

# Logs de todos os pods
kubectl logs -f -l app=portal -n automatizase

# Logs de pod específico
kubectl logs -f <pod-name> -n automatizase

# Logs dos últimos 100 linhas
kubectl logs --tail=100 deployment/portal -n automatizase

8.2 Acessar Container (Debug)

# Abrir shell no container
kubectl exec -it deployment/portal -n automatizase -- sh

# Executar comando único
kubectl exec deployment/portal -n automatizase -- env | grep NEXT_PUBLIC

8.3 Eventos do Cluster

# Ver eventos recentes do namespace
kubectl get events -n automatizase --sort-by='.lastTimestamp'

📊 Seção 9: Scaling

9.1 Escalar Manualmente

# Aumentar para 3 replicas
kubectl scale deployment/portal --replicas=3 -n automatizase

# Diminuir para 1 replica
kubectl scale deployment/portal --replicas=1 -n automatizase

9.2 Autoscaling (HPA) - Opcional

# Criar Horizontal Pod Autoscaler
kubectl autoscale deployment portal \
  --cpu-percent=70 \
  --min=2 \
  --max=10 \
  -n automatizase

# Verificar HPA
kubectl get hpa -n automatizase

🗑️ Seção 10: Remoção Completa

10.1 Deletar Aplicação

# Deletar todos os recursos
kubectl delete -f k8s/ingress.yaml
kubectl delete -f k8s/service.yaml
kubectl delete -f k8s/deployment.yaml
kubectl delete secret portal-secrets -n automatizase
kubectl delete -f k8s/namespace.yaml

10.2 Deletar Namespace (Remove Tudo)

# ⚠️ CUIDADO: Isso deleta TODOS os recursos no namespace
kubectl delete namespace automatizase

📝 Checklist de Deploy

Use este checklist para garantir que todos os passos foram executados:

  • Docker instalado e funcionando
  • kubectl configurado e conectado ao cluster
  • Imagem Docker construída e enviada ao registry
  • Secret portal-secrets criado com todas as variáveis
  • Namespace automatizase criado
  • Deployment aplicado e pods rodando
  • Service criado e expondo pods
  • Ingress criado e funcionando
  • DNS apontando para LoadBalancer IP
  • Certificado TLS configurado e válido
  • Health check respondendo: /api/health
  • Aplicação acessível via https://portal.automatizase.com.br
  • Logs sem erros críticos
  • Monitoramento configurado (opcional)

📞 Suporte

Para problemas ou dúvidas:

  • Verificar logs: kubectl logs -f deployment/portal -n automatizase
  • Verificar eventos: kubectl get events -n automatizase
  • Contato DevOps: devops@automatizase.com.br

Versão: 1.0 Última Atualização: 2025-01-15 Autor: James (Dev Agent)