581 lines
11 KiB
Markdown
581 lines
11 KiB
Markdown
# Deploy e Configuração - DRE Gerencial
|
|
|
|
## Visão Geral
|
|
|
|
Este guia cobre o processo completo de deploy e configuração do sistema DRE Gerencial em diferentes ambientes.
|
|
|
|
## Pré-requisitos
|
|
|
|
### 1. **Ambiente de Desenvolvimento**
|
|
- Node.js 18+
|
|
- PostgreSQL 13+
|
|
- npm ou yarn
|
|
- Git
|
|
|
|
### 2. **Ambiente de Produção**
|
|
- Servidor Linux (Ubuntu 20.04+ recomendado)
|
|
- PostgreSQL 13+
|
|
- Nginx (opcional, para proxy reverso)
|
|
- PM2 ou similar (para gerenciamento de processos)
|
|
|
|
## Configuração do Ambiente
|
|
|
|
### 1. **Variáveis de Ambiente**
|
|
|
|
#### Desenvolvimento (`.env.local`)
|
|
```env
|
|
# Database
|
|
POSTGRES_DB=dre_gerencial
|
|
POSTGRES_HOST=localhost
|
|
POSTGRES_PORT=5432
|
|
POSTGRES_USER=postgres
|
|
POSTGRES_PASSWORD=dev_password
|
|
|
|
# Next.js
|
|
NEXT_PUBLIC_APP_URL=http://localhost:3000
|
|
NODE_ENV=development
|
|
```
|
|
|
|
#### Produção (`.env.production`)
|
|
```env
|
|
# Database
|
|
POSTGRES_DB=dre_gerencial_prod
|
|
POSTGRES_HOST=prod-db-host
|
|
POSTGRES_PORT=5432
|
|
POSTGRES_USER=prod_user
|
|
POSTGRES_PASSWORD=secure_prod_password
|
|
|
|
# Next.js
|
|
NEXT_PUBLIC_APP_URL=https://dre-gerencial.com
|
|
NODE_ENV=production
|
|
|
|
# Security
|
|
NEXTAUTH_SECRET=your-secret-key
|
|
NEXTAUTH_URL=https://dre-gerencial.com
|
|
```
|
|
|
|
### 2. **Configuração do Banco de Dados**
|
|
|
|
#### Desenvolvimento
|
|
```bash
|
|
# Criar banco de desenvolvimento
|
|
createdb dre_gerencial
|
|
|
|
# Conectar e verificar
|
|
psql -h localhost -U postgres -d dre_gerencial
|
|
```
|
|
|
|
#### Produção
|
|
```bash
|
|
# Criar usuário e banco de produção
|
|
sudo -u postgres psql
|
|
CREATE USER prod_user WITH PASSWORD 'secure_prod_password';
|
|
CREATE DATABASE dre_gerencial_prod OWNER prod_user;
|
|
GRANT ALL PRIVILEGES ON DATABASE dre_gerencial_prod TO prod_user;
|
|
\q
|
|
```
|
|
|
|
## Deploy Local
|
|
|
|
### 1. **Desenvolvimento**
|
|
```bash
|
|
# Instalar dependências
|
|
npm install
|
|
|
|
# Executar migrações
|
|
npx drizzle-kit migrate
|
|
|
|
# Iniciar servidor de desenvolvimento
|
|
npm run dev
|
|
```
|
|
|
|
### 2. **Build de Produção Local**
|
|
```bash
|
|
# Build otimizado
|
|
npm run build
|
|
|
|
# Iniciar servidor de produção
|
|
npm run start
|
|
```
|
|
|
|
## Deploy em Servidor
|
|
|
|
### 1. **Preparação do Servidor**
|
|
|
|
#### Instalar Node.js
|
|
```bash
|
|
# Ubuntu/Debian
|
|
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
|
|
sudo apt-get install -y nodejs
|
|
|
|
# Verificar instalação
|
|
node --version
|
|
npm --version
|
|
```
|
|
|
|
#### Instalar PostgreSQL
|
|
```bash
|
|
# Ubuntu/Debian
|
|
sudo apt update
|
|
sudo apt install postgresql postgresql-contrib
|
|
|
|
# Iniciar serviço
|
|
sudo systemctl start postgresql
|
|
sudo systemctl enable postgresql
|
|
```
|
|
|
|
#### Instalar PM2 (Gerenciador de Processos)
|
|
```bash
|
|
# Instalar PM2 globalmente
|
|
sudo npm install -g pm2
|
|
|
|
# Configurar PM2 para iniciar com o sistema
|
|
pm2 startup
|
|
pm2 save
|
|
```
|
|
|
|
### 2. **Deploy da Aplicação**
|
|
|
|
#### Clonar Repositório
|
|
```bash
|
|
# Criar diretório da aplicação
|
|
sudo mkdir -p /var/www/dre-gerencial
|
|
sudo chown $USER:$USER /var/www/dre-gerencial
|
|
|
|
# Clonar repositório
|
|
cd /var/www/dre-gerencial
|
|
git clone <repository-url> .
|
|
|
|
# Instalar dependências
|
|
npm install --production
|
|
```
|
|
|
|
#### Configurar Variáveis de Ambiente
|
|
```bash
|
|
# Criar arquivo de ambiente de produção
|
|
cp .env.example .env.production
|
|
|
|
# Editar variáveis
|
|
nano .env.production
|
|
```
|
|
|
|
#### Build da Aplicação
|
|
```bash
|
|
# Build para produção
|
|
npm run build
|
|
|
|
# Verificar se build foi bem-sucedido
|
|
ls -la .next/
|
|
```
|
|
|
|
#### Configurar PM2
|
|
```bash
|
|
# Criar arquivo de configuração PM2
|
|
cat > ecosystem.config.js << EOF
|
|
module.exports = {
|
|
apps: [{
|
|
name: 'dre-gerencial',
|
|
script: 'npm',
|
|
args: 'start',
|
|
cwd: '/var/www/dre-gerencial',
|
|
instances: 1,
|
|
autorestart: true,
|
|
watch: false,
|
|
max_memory_restart: '1G',
|
|
env: {
|
|
NODE_ENV: 'production',
|
|
PORT: 3000
|
|
}
|
|
}]
|
|
};
|
|
EOF
|
|
|
|
# Iniciar aplicação
|
|
pm2 start ecosystem.config.js
|
|
|
|
# Verificar status
|
|
pm2 status
|
|
pm2 logs dre-gerencial
|
|
```
|
|
|
|
### 3. **Configuração do Nginx (Opcional)**
|
|
|
|
#### Instalar Nginx
|
|
```bash
|
|
sudo apt install nginx
|
|
sudo systemctl start nginx
|
|
sudo systemctl enable nginx
|
|
```
|
|
|
|
#### Configurar Proxy Reverso
|
|
```bash
|
|
# Criar configuração do site
|
|
sudo nano /etc/nginx/sites-available/dre-gerencial
|
|
|
|
# Conteúdo do arquivo
|
|
server {
|
|
listen 80;
|
|
server_name dre-gerencial.com www.dre-gerencial.com;
|
|
|
|
location / {
|
|
proxy_pass http://localhost:3000;
|
|
proxy_http_version 1.1;
|
|
proxy_set_header Upgrade $http_upgrade;
|
|
proxy_set_header Connection 'upgrade';
|
|
proxy_set_header Host $host;
|
|
proxy_set_header X-Real-IP $remote_addr;
|
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
proxy_set_header X-Forwarded-Proto $scheme;
|
|
proxy_cache_bypass $http_upgrade;
|
|
}
|
|
}
|
|
|
|
# Habilitar site
|
|
sudo ln -s /etc/nginx/sites-available/dre-gerencial /etc/nginx/sites-enabled/
|
|
|
|
# Testar configuração
|
|
sudo nginx -t
|
|
|
|
# Recarregar Nginx
|
|
sudo systemctl reload nginx
|
|
```
|
|
|
|
#### Configurar SSL com Let's Encrypt
|
|
```bash
|
|
# Instalar Certbot
|
|
sudo apt install certbot python3-certbot-nginx
|
|
|
|
# Obter certificado SSL
|
|
sudo certbot --nginx -d dre-gerencial.com -d www.dre-gerencial.com
|
|
|
|
# Verificar renovação automática
|
|
sudo certbot renew --dry-run
|
|
```
|
|
|
|
## Deploy com Docker
|
|
|
|
### 1. **Dockerfile**
|
|
```dockerfile
|
|
# Dockerfile
|
|
FROM node:18-alpine AS base
|
|
|
|
# Install dependencies only when needed
|
|
FROM base AS deps
|
|
RUN apk add --no-cache libc6-compat
|
|
WORKDIR /app
|
|
|
|
# Install dependencies based on the preferred package manager
|
|
COPY package.json package-lock.json* ./
|
|
RUN npm ci --only=production
|
|
|
|
# Rebuild the source code only when needed
|
|
FROM base AS builder
|
|
WORKDIR /app
|
|
COPY --from=deps /app/node_modules ./node_modules
|
|
COPY . .
|
|
|
|
# Build the application
|
|
RUN npm run build
|
|
|
|
# Production image, copy all the files and run next
|
|
FROM base AS runner
|
|
WORKDIR /app
|
|
|
|
ENV NODE_ENV production
|
|
|
|
RUN addgroup --system --gid 1001 nodejs
|
|
RUN adduser --system --uid 1001 nextjs
|
|
|
|
COPY --from=builder /app/public ./public
|
|
|
|
# Set the correct permission for prerender cache
|
|
RUN mkdir .next
|
|
RUN chown nextjs:nodejs .next
|
|
|
|
# Automatically leverage output traces to reduce image size
|
|
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
|
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
|
|
|
USER nextjs
|
|
|
|
EXPOSE 3000
|
|
|
|
ENV PORT 3000
|
|
ENV HOSTNAME "0.0.0.0"
|
|
|
|
CMD ["node", "server.js"]
|
|
```
|
|
|
|
### 2. **Docker Compose**
|
|
```yaml
|
|
# docker-compose.yml
|
|
version: '3.8'
|
|
|
|
services:
|
|
app:
|
|
build: .
|
|
ports:
|
|
- "3000:3000"
|
|
environment:
|
|
- NODE_ENV=production
|
|
- POSTGRES_DB=dre_gerencial
|
|
- POSTGRES_HOST=db
|
|
- POSTGRES_PORT=5432
|
|
- POSTGRES_USER=postgres
|
|
- POSTGRES_PASSWORD=password
|
|
depends_on:
|
|
- db
|
|
restart: unless-stopped
|
|
|
|
db:
|
|
image: postgres:13
|
|
environment:
|
|
- POSTGRES_DB=dre_gerencial
|
|
- POSTGRES_USER=postgres
|
|
- POSTGRES_PASSWORD=password
|
|
volumes:
|
|
- postgres_data:/var/lib/postgresql/data
|
|
ports:
|
|
- "5432:5432"
|
|
restart: unless-stopped
|
|
|
|
volumes:
|
|
postgres_data:
|
|
```
|
|
|
|
### 3. **Deploy com Docker**
|
|
```bash
|
|
# Build e executar
|
|
docker-compose up -d
|
|
|
|
# Verificar logs
|
|
docker-compose logs -f app
|
|
|
|
# Parar serviços
|
|
docker-compose down
|
|
```
|
|
|
|
## Deploy Automatizado
|
|
|
|
### 1. **GitHub Actions**
|
|
|
|
#### Workflow de Deploy
|
|
```yaml
|
|
# .github/workflows/deploy.yml
|
|
name: Deploy to Production
|
|
|
|
on:
|
|
push:
|
|
branches: [main]
|
|
|
|
jobs:
|
|
deploy:
|
|
runs-on: ubuntu-latest
|
|
|
|
steps:
|
|
- uses: actions/checkout@v3
|
|
|
|
- name: Setup Node.js
|
|
uses: actions/setup-node@v3
|
|
with:
|
|
node-version: '18'
|
|
cache: 'npm'
|
|
|
|
- name: Install dependencies
|
|
run: npm ci
|
|
|
|
- name: Run tests
|
|
run: npm test
|
|
|
|
- name: Build application
|
|
run: npm run build
|
|
|
|
- name: Deploy to server
|
|
uses: appleboy/ssh-action@v0.1.5
|
|
with:
|
|
host: ${{ secrets.HOST }}
|
|
username: ${{ secrets.USERNAME }}
|
|
key: ${{ secrets.SSH_KEY }}
|
|
script: |
|
|
cd /var/www/dre-gerencial
|
|
git pull origin main
|
|
npm ci --production
|
|
npm run build
|
|
pm2 restart dre-gerencial
|
|
```
|
|
|
|
### 2. **Configuração de Secrets**
|
|
No GitHub, adicionar os seguintes secrets:
|
|
- `HOST`: IP do servidor
|
|
- `USERNAME`: usuário do servidor
|
|
- `SSH_KEY`: chave SSH privada
|
|
|
|
## Monitoramento
|
|
|
|
### 1. **PM2 Monitoring**
|
|
```bash
|
|
# Monitorar aplicação
|
|
pm2 monit
|
|
|
|
# Ver logs em tempo real
|
|
pm2 logs dre-gerencial --lines 100
|
|
|
|
# Reiniciar aplicação
|
|
pm2 restart dre-gerencial
|
|
|
|
# Parar aplicação
|
|
pm2 stop dre-gerencial
|
|
```
|
|
|
|
### 2. **Logs do Sistema**
|
|
```bash
|
|
# Logs do Nginx
|
|
sudo tail -f /var/log/nginx/access.log
|
|
sudo tail -f /var/log/nginx/error.log
|
|
|
|
# Logs do PostgreSQL
|
|
sudo tail -f /var/log/postgresql/postgresql-13-main.log
|
|
```
|
|
|
|
### 3. **Monitoramento de Recursos**
|
|
```bash
|
|
# Uso de CPU e memória
|
|
htop
|
|
|
|
# Espaço em disco
|
|
df -h
|
|
|
|
# Status dos serviços
|
|
systemctl status nginx
|
|
systemctl status postgresql
|
|
```
|
|
|
|
## Backup e Restore
|
|
|
|
### 1. **Backup do Banco de Dados**
|
|
```bash
|
|
# Backup completo
|
|
pg_dump -h localhost -U postgres -d dre_gerencial_prod > backup_$(date +%Y%m%d).sql
|
|
|
|
# Backup apenas dados
|
|
pg_dump -h localhost -U postgres -d dre_gerencial_prod --data-only > data_backup_$(date +%Y%m%d).sql
|
|
|
|
# Backup apenas schema
|
|
pg_dump -h localhost -U postgres -d dre_gerencial_prod --schema-only > schema_backup_$(date +%Y%m%d).sql
|
|
```
|
|
|
|
### 2. **Restore do Banco de Dados**
|
|
```bash
|
|
# Restore completo
|
|
psql -h localhost -U postgres -d dre_gerencial_prod < backup_20240101.sql
|
|
|
|
# Restore apenas dados
|
|
psql -h localhost -U postgres -d dre_gerencial_prod < data_backup_20240101.sql
|
|
```
|
|
|
|
### 3. **Backup Automático**
|
|
```bash
|
|
# Criar script de backup
|
|
cat > /home/user/backup_dre.sh << EOF
|
|
#!/bin/bash
|
|
DATE=$(date +%Y%m%d_%H%M%S)
|
|
BACKUP_DIR="/home/user/backups"
|
|
DB_NAME="dre_gerencial_prod"
|
|
|
|
mkdir -p $BACKUP_DIR
|
|
|
|
# Backup do banco
|
|
pg_dump -h localhost -U postgres -d $DB_NAME > $BACKUP_DIR/dre_backup_$DATE.sql
|
|
|
|
# Manter apenas os últimos 7 backups
|
|
cd $BACKUP_DIR
|
|
ls -t dre_backup_*.sql | tail -n +8 | xargs -r rm
|
|
|
|
echo "Backup completed: dre_backup_$DATE.sql"
|
|
EOF
|
|
|
|
# Tornar executável
|
|
chmod +x /home/user/backup_dre.sh
|
|
|
|
# Agendar backup diário
|
|
crontab -e
|
|
# Adicionar linha:
|
|
0 2 * * * /home/user/backup_dre.sh
|
|
```
|
|
|
|
## Troubleshooting
|
|
|
|
### 1. **Problemas Comuns**
|
|
|
|
#### Aplicação não inicia
|
|
```bash
|
|
# Verificar logs
|
|
pm2 logs dre-gerencial
|
|
|
|
# Verificar se porta está em uso
|
|
netstat -tlnp | grep :3000
|
|
|
|
# Verificar variáveis de ambiente
|
|
pm2 env 0
|
|
```
|
|
|
|
#### Erro de conexão com banco
|
|
```bash
|
|
# Verificar se PostgreSQL está rodando
|
|
sudo systemctl status postgresql
|
|
|
|
# Testar conexão
|
|
psql -h localhost -U postgres -d dre_gerencial_prod
|
|
|
|
# Verificar logs do PostgreSQL
|
|
sudo tail -f /var/log/postgresql/postgresql-13-main.log
|
|
```
|
|
|
|
#### Erro de permissões
|
|
```bash
|
|
# Verificar permissões do diretório
|
|
ls -la /var/www/dre-gerencial
|
|
|
|
# Corrigir permissões
|
|
sudo chown -R $USER:$USER /var/www/dre-gerencial
|
|
chmod -R 755 /var/www/dre-gerencial
|
|
```
|
|
|
|
### 2. **Comandos Úteis**
|
|
|
|
#### Reiniciar serviços
|
|
```bash
|
|
# Reiniciar aplicação
|
|
pm2 restart dre-gerencial
|
|
|
|
# Reiniciar Nginx
|
|
sudo systemctl restart nginx
|
|
|
|
# Reiniciar PostgreSQL
|
|
sudo systemctl restart postgresql
|
|
```
|
|
|
|
#### Verificar status
|
|
```bash
|
|
# Status da aplicação
|
|
pm2 status
|
|
|
|
# Status dos serviços do sistema
|
|
sudo systemctl status nginx postgresql
|
|
|
|
# Uso de recursos
|
|
free -h
|
|
df -h
|
|
```
|
|
|
|
## Próximos Passos
|
|
|
|
1. **Implementar CI/CD** completo
|
|
2. **Adicionar monitoramento** com Prometheus/Grafana
|
|
3. **Implementar backup** automatizado
|
|
4. **Adicionar alertas** por email/Slack
|
|
5. **Implementar load balancing** para alta disponibilidade
|
|
6. **Adicionar CDN** para assets estáticos
|
|
7. **Implementar cache** com Redis
|
|
8. **Adicionar health checks** automatizados
|