BCards-Scripts-Server/scripts/setup-nginx-loadbalancer.sh
2025-07-22 21:24:07 -03:00

196 lines
5.3 KiB
Bash

#!/bin/bash
# Setup NGINX Load Balancer for BCards
# Configura NGINX para fazer load balance entre os servidores
set -e
LOADBALANCER_IP="141.148.162.114" # Usar primeiro servidor como load balancer
SSH_USER="ubuntu"
DOMAIN="bcards.site"
# Cores para output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
log() {
echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] $1${NC}"
}
error() {
echo -e "${RED}[ERROR] $1${NC}"
exit 1
}
warn() {
echo -e "${YELLOW}[WARNING] $1${NC}"
}
info() {
echo -e "${BLUE}[INFO] $1${NC}"
}
# Função para executar comando em servidor remoto
run_remote() {
local server_ip=$1
local command=$2
ssh -o StrictHostKeyChecking=no ${SSH_USER}@${server_ip} "$command"
}
# Verificar conectividade
check_connectivity() {
log "Verificando conectividade com o load balancer..."
if ! ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no ${SSH_USER}@${LOADBALANCER_IP} "echo 'ok'" >/dev/null 2>&1; then
error "Não foi possível conectar ao servidor $LOADBALANCER_IP"
fi
info "✓ Conectividade OK"
}
# Configurar NGINX como load balancer
setup_nginx_loadbalancer() {
log "Configurando NGINX Load Balancer..."
# Copiar arquivo de configuração
scp nginx/nginx-loadbalancer.conf ${SSH_USER}@${LOADBALANCER_IP}:/tmp/
# Configurar NGINX
run_remote $LOADBALANCER_IP "
# Backup da configuração atual
sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.backup 2>/dev/null || true
# Instalar configuração do load balancer
sudo cp /tmp/nginx-loadbalancer.conf /etc/nginx/sites-available/bcards
sudo ln -sf /etc/nginx/sites-available/bcards /etc/nginx/sites-enabled/
# Remover site padrão
sudo rm -f /etc/nginx/sites-enabled/default
# Testar configuração
sudo nginx -t
# Restart NGINX
sudo systemctl restart nginx
sudo systemctl enable nginx
"
info "✓ NGINX Load Balancer configurado"
}
# Configurar SSL com Let's Encrypt
setup_ssl() {
log "Configurando SSL com Let's Encrypt..."
run_remote $LOADBALANCER_IP "
# Parar NGINX temporariamente para certbot
sudo systemctl stop nginx
# Obter certificado SSL
sudo certbot certonly --standalone -d $DOMAIN -d www.$DOMAIN --non-interactive --agree-tos --email admin@$DOMAIN
# Restart NGINX
sudo systemctl start nginx
# Configurar renovação automática
echo '0 2 * * * root certbot renew --quiet && systemctl reload nginx' | sudo tee -a /etc/crontab
"
info "✓ SSL configurado com Let's Encrypt"
}
# Configurar firewall para load balancer
configure_firewall() {
log "Configurando firewall para load balancer..."
run_remote $LOADBALANCER_IP "
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw reload
"
info "✓ Firewall configurado"
}
# Testar load balancer
test_loadbalancer() {
log "Testando load balancer..."
# Teste HTTP (deve redirecionar para HTTPS)
info "Testando redirecionamento HTTP para HTTPS..."
local http_status=$(curl -s -o /dev/null -w "%{http_code}" -L http://$DOMAIN/health)
if [ "$http_status" = "200" ]; then
info "✓ Redirecionamento HTTP->HTTPS funcionando"
else
warn "HTTP test retornou status: $http_status"
fi
# Teste HTTPS
info "Testando HTTPS..."
local https_status=$(curl -s -o /dev/null -w "%{http_code}" -k https://$DOMAIN/health)
if [ "$https_status" = "200" ]; then
info "✓ HTTPS funcionando"
else
warn "HTTPS test retornou status: $https_status"
fi
# Mostrar logs do NGINX
info "Últimos logs do NGINX:"
run_remote $LOADBALANCER_IP "sudo tail -n 20 /var/log/nginx/bcards_access.log" || true
run_remote $LOADBALANCER_IP "sudo tail -n 10 /var/log/nginx/bcards_error.log" || true
}
# Função principal
main() {
log "Configurando NGINX Load Balancer para BCards..."
check_connectivity
setup_nginx_loadbalancer
configure_firewall
if [[ "$1" == "--ssl" ]]; then
setup_ssl
else
warn "SSL não configurado. Use --ssl para configurar automaticamente."
info "Para configurar SSL manualmente:"
info " sudo certbot --nginx -d $DOMAIN -d www.$DOMAIN"
fi
test_loadbalancer
log "Setup do Load Balancer concluído!"
info "Load Balancer: $LOADBALANCER_IP"
info "Domain: $DOMAIN"
info "Backends: 129.153.123.92:8080, 129.146.116.218:8080"
if [[ "$1" == "--ssl" ]]; then
info "Acesso: https://$DOMAIN"
else
info "Acesso: http://$DOMAIN (configurar SSL depois)"
fi
}
# Mostrar help
if [[ "$1" == "--help" || "$1" == "-h" ]]; then
echo "Setup NGINX Load Balancer for BCards"
echo ""
echo "Usage: $0 [OPTIONS]"
echo ""
echo "OPTIONS:"
echo " --ssl Configurar SSL automaticamente com Let's Encrypt"
echo " --help Mostrar esta ajuda"
echo ""
echo "Examples:"
echo " $0 # Setup sem SSL"
echo " $0 --ssl # Setup com SSL automático"
echo ""
echo "Load Balancer: $LOADBALANCER_IP"
echo "Domain: $DOMAIN"
exit 0
fi
# Executar função principal
main "$@"