diff --git a/Actualización.md b/Actualización.md new file mode 100644 index 0000000..8c030ab --- /dev/null +++ b/Actualización.md @@ -0,0 +1,289 @@ +# Actualización + +Mantén NetBox y sus componentes actualizados de forma segura. + +## Antes de Actualizar + +### 1. Backup Completo + +```bash +# Ejecutar script de backup +/root/backup-netbox.sh + +# O manualmente +docker exec netbox-db pg_dump -U netbox netbox | gzip > netbox-pre-update-$(date +%Y%m%d).sql.gz +``` + +### 2. Verificar Notas de Release + +- [NetBox Releases](https://github.com/netbox-community/netbox/releases) +- [LinuxServer Announcements](https://github.com/linuxserver/docker-netbox/releases) +- Revisar breaking changes y migraciones de BD + +### 3. Planificar Ventana de Mantenimiento + +- Actualizar en horario de bajo uso +- Informar a usuarios +- Preparar rollback si es necesario + +--- + +## Actualizar NetBox + +### Método 1: Pull de Imagen + +```bash +# 1. Backup +docker exec netbox-db pg_dump -U netbox netbox > netbox-pre-update.sql + +# 2. Detener stack +docker stop netbox netbox-redis netbox-db + +# 3. Actualizar imágenes +docker pull lscr.io/linuxserver/netbox:latest + +# 4. Iniciar stack +docker start netbox-db +sleep 10 +docker start netbox-redis +sleep 5 +docker start netbox + +# 5. Verificar logs +docker logs -f netbox +``` + +### Método 2: Recrear Contenedores (Portainer) + +1. Ve al stack en Portainer +2. Click en **Pull and redeploy** +3. Verifica logs del contenedor + +### Verificar Actualización + +```bash +# Ver versión actual +docker exec netbox python /app/netbox/manage.py version + +# Ver logs de migración +docker logs netbox | grep -i migration + +# Verificar en UI +# Admin → System → About +``` + +--- + +## Actualizar PostgreSQL + +### De PostgreSQL 16 a 18 + +Si vienes de una versión anterior con PostgreSQL 16: + +```bash +# 1. BACKUP CRÍTICO +docker exec netbox-db pg_dump -U netbox netbox > netbox-pg-migration-$(date +%Y%m%d).sql + +# 2. Detener NetBox y Redis +docker stop netbox netbox-redis + +# 3. Detener y eliminar PostgreSQL 16 +docker stop netbox-db +docker rm netbox-db + +# 4. Eliminar volumen antiguo +docker volume rm netbox_db + +# 5. Recrear volumen +docker volume create netbox_db + +# 6. Actualizar compose a postgres:18-alpine +# Editar docker-compose.yml si es necesario + +# 7. Iniciar PostgreSQL 18 +docker compose up -d netbox-db + +# 8. Esperar que esté listo +sleep 10 +docker exec netbox-db pg_isready -U netbox + +# 9. Restaurar datos +cat netbox-pg-migration-20250101.sql | docker exec -i netbox-db psql -U netbox netbox + +# 10. Iniciar servicios +docker start netbox-redis +sleep 5 +docker start netbox + +# 11. Verificar +docker logs -f netbox +``` + +--- + +## Actualizar Redis + +Redis 7 es muy estable, pero si necesitas actualizar: + +```bash +# 1. Detener NetBox +docker stop netbox + +# 2. Actualizar Redis +docker stop netbox-redis +docker pull redis:7-alpine +docker start netbox-redis + +# 3. Reiniciar NetBox +docker start netbox +``` + +> ℹ️ Redis solo almacena caché, no es crítico hacer backup + +--- + +## Actualizar Plugins + +```bash +# Entrar al contenedor +docker exec -it netbox bash + +# Ver plugins instalados +pip list | grep netbox + +# Actualizar plugin específico +pip install --upgrade netbox-topology-views + +# Actualizar todos los plugins +pip list --outdated | grep netbox- | cut -d' ' -f1 | xargs pip install --upgrade + +# Salir +exit + +# Reiniciar NetBox +docker restart netbox +``` + +--- + +## Rollback (Si Algo Falla) + +### Rollback Rápido + +```bash +# 1. Detener NetBox +docker stop netbox + +# 2. Restaurar base de datos +gunzip < netbox-pre-update-20250101.sql.gz | docker exec -i netbox-db psql -U netbox netbox + +# 3. Volver a imagen anterior (si guardaste el tag) +docker tag lscr.io/linuxserver/netbox:3.6.9 lscr.io/linuxserver/netbox:latest + +# 4. Recrear contenedor +docker stop netbox +docker rm netbox +docker compose up -d netbox + +# 5. Verificar +docker logs -f netbox +``` + +### Rollback Completo + +```bash +# Restaurar desde backup completo +# Ver sección "Restauración Completa" en Backup y Restauración +``` + +--- + +## Automatizar Actualizaciones + +### Watchtower (No Recomendado para Producción) + +Si quieres auto-actualizar (úsalo solo en dev/test): + +```yaml +services: + watchtower: + image: containrrr/watchtower + volumes: + - /var/run/docker.sock:/var/run/docker.sock + command: --interval 86400 --cleanup +``` + +### Script de Actualización Controlada + +```bash +#!/bin/bash +# /root/update-netbox.sh + +# Backup pre-actualización +docker exec netbox-db pg_dump -U netbox netbox | gzip > /backups/netbox/netbox-pre-update-$(date +%Y%m%d).sql.gz + +# Detener +docker stop netbox netbox-redis + +# Actualizar imágenes +docker pull lscr.io/linuxserver/netbox:latest +docker pull redis:7-alpine + +# Iniciar +docker start netbox-redis +sleep 5 +docker start netbox + +# Verificar +sleep 10 +if docker ps | grep -q netbox; then + echo "✓ NetBox actualizado correctamente" +else + echo "✗ Error en actualización - revisar logs" + exit 1 +fi +``` + +Ejecuta manualmente o programa: + +```bash +# Cron mensual (primer domingo a las 3 AM) +0 3 1-7 * 0 /root/update-netbox.sh >> /var/log/netbox-update.log 2>&1 +``` + +--- + +## Verificación Post-Actualización + +### Checklist + +- [ ] NetBox accesible vía web +- [ ] Login funciona +- [ ] API responde: `curl -H "Authorization: Token TOKEN" https://netbox.example.com/api/` +- [ ] Plugins funcionan +- [ ] Datos intactos (verificar dispositivos/IPs) +- [ ] Webhooks operativos +- [ ] Scripts personalizados funcionan + +### Comandos de Verificación + +```bash +# Versión +docker exec netbox python /app/netbox/manage.py version + +# Migraciones pendientes +docker exec netbox python /app/netbox/manage.py showmigrations | grep "\[ \]" + +# Estado de servicios +docker ps -a | grep netbox + +# Uso de recursos +docker stats netbox netbox-db netbox-redis --no-stream +``` + +--- + +## Próximos Pasos + +1. **[Backup](Backup-y-Restauración)** - Automatiza backups post-actualización +2. **[Solución de Problemas](Solución-de-Problemas)** - Si encuentras problemas diff --git a/Backup-y-Restauración.md b/Backup-y-Restauración.md new file mode 100644 index 0000000..50804d5 --- /dev/null +++ b/Backup-y-Restauración.md @@ -0,0 +1,292 @@ +# Backup y Restauración + +Protege tus datos de NetBox con backups automáticos. + +## Qué Hacer Backup + +NetBox tiene 3 componentes críticos: + +1. **PostgreSQL** - Base de datos (lo más importante) +2. **Configuración** - `/config/` (configuration.py, plugins, scripts) +3. **Redis** - Solo caché temporal (opcional) + +--- + +## Backup Manual + +### PostgreSQL (Crítico) + +```bash +# Backup completo +docker exec netbox-db pg_dump -U netbox netbox > netbox-backup-$(date +%Y%m%d).sql + +# Backup comprimido (ahorra espacio) +docker exec netbox-db pg_dump -U netbox netbox | gzip > netbox-backup-$(date +%Y%m%d).sql.gz + +# Verificar backup +gunzip -c netbox-backup-20250101.sql.gz | head -20 +``` + +### Configuración + +```bash +# Backup del volumen de configuración +docker run --rm -v netbox_config:/backup -v $(pwd):/target alpine tar czf /target/netbox-config-$(date +%Y%m%d).tar.gz -C /backup . + +# Verificar +tar tzf netbox-config-20250101.tar.gz | head +``` + +### Redis (Opcional) + +```bash +# Forzar guardado +docker exec netbox-redis redis-cli --pass "TU_REDIS_PASSWORD" SAVE + +# Backup del dump +docker run --rm -v netbox_redis:/backup -v $(pwd):/target alpine tar czf /target/netbox-redis-$(date +%Y%m%d).tar.gz -C /backup . +``` + +--- + +## Backup Automático + +### Script de Backup + +Crea `/root/backup-netbox.sh`: + +```bash +#!/bin/bash + +# Configuración +BACKUP_DIR="/backups/netbox" +DATE=$(date +%Y%m%d-%H%M%S) +RETENTION_DAYS=7 + +# Crear directorio +mkdir -p $BACKUP_DIR + +# PostgreSQL (comprimido) +echo "Backing up PostgreSQL..." +docker exec netbox-db pg_dump -U netbox netbox | gzip > $BACKUP_DIR/netbox-db-$DATE.sql.gz + +# Configuración +echo "Backing up configuration..." +docker run --rm -v netbox_config:/backup -v $BACKUP_DIR:/target alpine tar czf /target/netbox-config-$DATE.tar.gz -C /backup . + +# Redis (opcional) +# docker exec netbox-redis redis-cli --pass "PASSWORD" SAVE +# docker run --rm -v netbox_redis:/backup -v $BACKUP_DIR:/target alpine tar czf /target/netbox-redis-$DATE.tar.gz -C /backup . + +# Limpiar backups antiguos +echo "Cleaning old backups (older than $RETENTION_DAYS days)..." +find $BACKUP_DIR -name "netbox-db-*.sql.gz" -mtime +$RETENTION_DAYS -delete +find $BACKUP_DIR -name "netbox-config-*.tar.gz" -mtime +$RETENTION_DAYS -delete + +# Verificar espacio +BACKUP_SIZE=$(du -sh $BACKUP_DIR | cut -f1) +echo "Backup completed: $DATE" +echo "Backup size: $BACKUP_SIZE" + +# Opcional: copiar a otro servidor +# rsync -avz $BACKUP_DIR/ backup@remote:/backups/netbox/ +``` + +Hazlo ejecutable: + +```bash +chmod +x /root/backup-netbox.sh +``` + +### Automatizar con Cron + +```bash +# Editar crontab +crontab -e + +# Añadir backup diario a las 2 AM +0 2 * * * /root/backup-netbox.sh >> /var/log/netbox-backup.log 2>&1 + +# Backup cada 6 horas +0 */6 * * * /root/backup-netbox.sh >> /var/log/netbox-backup.log 2>&1 +``` + +### Verificar Cron + +```bash +# Ver tareas programadas +crontab -l + +# Ver logs de backup +tail -f /var/log/netbox-backup.log +``` + +--- + +## Restauración + +### Restaurar PostgreSQL + +```bash +# Detener NetBox +docker stop netbox + +# Restaurar desde backup comprimido +gunzip < netbox-backup-20250101.sql.gz | docker exec -i netbox-db psql -U netbox netbox + +# O desde backup sin comprimir +cat netbox-backup-20250101.sql | docker exec -i netbox-db psql -U netbox netbox + +# Reiniciar NetBox +docker start netbox + +# Verificar logs +docker logs -f netbox +``` + +### Restaurar Configuración + +```bash +# Detener NetBox +docker stop netbox + +# Limpiar volumen actual (opcional - crear backup primero) +# docker run --rm -v netbox_config:/config alpine rm -rf /config/* + +# Restaurar desde backup +docker run --rm -v netbox_config:/restore -v $(pwd):/source alpine tar xzf /source/netbox-config-20250101.tar.gz -C /restore + +# Verificar permisos +docker run --rm -v netbox_config:/config alpine chown -R 1000:1000 /config + +# Reiniciar NetBox +docker start netbox +``` + +### Restauración Completa + +```bash +# 1. Detener stack +docker stop netbox netbox-redis netbox-db + +# 2. Eliminar volúmenes (CUIDADO - perderás datos actuales) +# docker volume rm netbox_db netbox_config + +# 3. Recrear volúmenes +docker volume create netbox_db +docker volume create netbox_config + +# 4. Restaurar PostgreSQL +docker start netbox-db +sleep 10 +gunzip < netbox-backup-20250101.sql.gz | docker exec -i netbox-db psql -U netbox netbox + +# 5. Restaurar configuración +docker run --rm -v netbox_config:/restore -v $(pwd):/source alpine tar xzf /source/netbox-config-20250101.tar.gz -C /restore + +# 6. Iniciar todo +docker start netbox-redis netbox + +# 7. Verificar +docker logs -f netbox +``` + +--- + +## Migración a Otro Servidor + +### Exportar + +En el servidor origen: + +```bash +# Backup completo +/root/backup-netbox.sh + +# Copiar a servidor destino +scp /backups/netbox/netbox-db-*.sql.gz user@destino:/tmp/ +scp /backups/netbox/netbox-config-*.tar.gz user@destino:/tmp/ +``` + +### Importar + +En el servidor destino: + +```bash +# Desplegar NetBox (sin iniciar) +docker compose up -d + +# Detener NetBox +docker stop netbox + +# Restaurar datos +gunzip < /tmp/netbox-db-20250101.sql.gz | docker exec -i netbox-db psql -U netbox netbox +docker run --rm -v netbox_config:/restore -v /tmp:/source alpine tar xzf /source/netbox-config-20250101.tar.gz -C /restore + +# Iniciar +docker start netbox +``` + +--- + +## Backup Remoto + +### Rsync a Servidor Remoto + +Añade al script de backup: + +```bash +# Al final de backup-netbox.sh +rsync -avz --delete $BACKUP_DIR/ backup@remote.server:/backups/netbox/ +``` + +### Backup a S3 + +```bash +# Instalar AWS CLI +apt install awscli + +# Configurar credenciales +aws configure + +# Añadir al script de backup +aws s3 sync $BACKUP_DIR/ s3://mi-bucket/netbox-backups/ --delete +``` + +--- + +## Verificación de Backups + +### Script de Verificación + +```bash +#!/bin/bash +LATEST_BACKUP=$(ls -t /backups/netbox/netbox-db-*.sql.gz | head -1) + +echo "Verificando backup: $LATEST_BACKUP" + +# Verificar integridad +gunzip -t $LATEST_BACKUP +if [ $? -eq 0 ]; then + echo "✓ Backup íntegro" +else + echo "✗ Backup corrupto" + exit 1 +fi + +# Verificar tamaño mínimo (ej: 1MB) +SIZE=$(stat -f%z "$LATEST_BACKUP") +if [ $SIZE -gt 1048576 ]; then + echo "✓ Tamaño válido: $(numfmt --to=iec $SIZE)" +else + echo "✗ Backup muy pequeño" + exit 1 +fi +``` + +--- + +## Próximos Pasos + +1. **[Actualización](Actualización)** - Mantén NetBox actualizado +2. **[Solución de Problemas](Solución-de-Problemas)** - Si algo falla diff --git a/Configuración-Inicial.md b/Configuración-Inicial.md new file mode 100644 index 0000000..4bdbc9f --- /dev/null +++ b/Configuración-Inicial.md @@ -0,0 +1,182 @@ +# Configuración Inicial + +Pasos para configurar NetBox tras el primer despliegue. + +## Primer Acceso + +1. Accede a NetBox mediante tu dominio configurado +2. Login con las credenciales del superusuario: + - **Email**: El valor de `SUPERUSER_EMAIL` + - **Password**: El valor de `SUPERUSER_PASSWORD` + +> ℹ️ El primer inicio puede tardar 1-2 minutos mientras NetBox inicializa la base de datos. + +--- + +## Panel de Administración + +### Usuarios y Permisos + +**Admin** → **Users** + +1. **Crear usuario adicional**: + - Click en **Add** + - Username, email, password + - Asignar a grupos + - Marcar **Staff status** si necesita acceso admin + +2. **Crear grupos**: + - **Admin** → **Groups** → **Add** + - Asignar permisos granulares por modelo + - Ejemplo: Grupo "Network Team" con permisos IPAM + +3. **Tokens de API**: + - **Admin** → **Tokens** → **Add** + - Seleccionar usuario + - Definir permisos (read-only, write) + - Usar para automatización + +--- + +## Configuración Básica + +### Sites (Ubicaciones) + +**Organization** → **Sites** → **Add** + +Crea tus ubicaciones físicas: +- **Name**: Madrid DC1 +- **Status**: Active +- **Region**: España +- **Facility**: Equinix +- **Physical Address**: Calle ejemplo 123 +- **GPS**: 40.4168, -3.7038 + +### Racks + +**DCIM** → **Racks** → **Add** + +Define racks para inventario: +- **Name**: RACK-01 +- **Site**: Madrid DC1 +- **U Height**: 42 +- **Type**: 4-post cabinet +- **Width**: 19 inches + +### Device Types + +**DCIM** → **Device Types** → **Add** + +O importa desde [Device Type Library](https://github.com/netbox-community/devicetype-library): + +```bash +# Desde el contenedor +docker exec -it netbox bash +cd /app/netbox +python manage.py import_device_types --url https://github.com/netbox-community/devicetype-library.git +``` + +### Prefijos de Red + +**IPAM** → **Prefixes** → **Add** + +Define tus redes: +- **Prefix**: 192.168.1.0/24 +- **Site**: Madrid DC1 +- **VLAN**: VLAN 10 - Servidores +- **Status**: Active +- **Role**: Servers +- **Description**: Red de servidores producción + +### VLANs + +**IPAM** → **VLANs** → **Add** + +- **ID**: 10 +- **Name**: Servidores +- **Site**: Madrid DC1 +- **Status**: Active + +--- + +## Configuración Avanzada + +### Custom Fields + +**Customization** → **Custom Fields** → **Add** + +Añade campos personalizados a cualquier modelo: + +**Ejemplo**: Número de contrato para dispositivos +- **Object Types**: DCIM > Device +- **Type**: Text +- **Name**: contract_number +- **Label**: Nº Contrato +- **Required**: No + +### Tags + +**Organization** → **Tags** → **Add** + +Etiquetas para organizar objetos: +- **Name**: Producción +- **Slug**: produccion +- **Color**: Red + +### Webhooks + +**System** → **Webhooks** → **Add** + +Integra con sistemas externos: +- **Name**: Notificar a Slack +- **Object Types**: DCIM > Device +- **Events**: Created, Updated, Deleted +- **URL**: `https://hooks.slack.com/services/...` +- **HTTP Method**: POST + +--- + +## Importar Datos + +### Desde CSV + +**Import** (en cada sección) + +Ejemplo para IPs: + +```csv +address,status,dns_name,description +192.168.1.10,active,server01.local,Web Server +192.168.1.11,active,server02.local,DB Server +``` + +### Desde API + +```python +import requests + +headers = { + 'Authorization': 'Token tu_token_aqui', + 'Content-Type': 'application/json' +} + +data = { + 'address': '192.168.1.20/32', + 'status': 'active', + 'dns_name': 'router01.local' +} + +response = requests.post( + 'https://netbox.tudominio.com/api/ipam/ip-addresses/', + headers=headers, + json=data +) +``` + +--- + +## Próximos Pasos + +1. **[Personalización](Personalización)** - LDAP, plugins, scripts +2. **[Backup](Backup-y-Restauración)** - Protege tus datos +3. **[API Docs](https://netbox.tudominio.com/api/docs/)** - Explora la API REST diff --git a/Home.md b/Home.md index 0ab951d..f39ffc7 100644 --- a/Home.md +++ b/Home.md @@ -1 +1,160 @@ -¡Bienvenidos a la Wiki! \ No newline at end of file +# NetBox Wiki + +Documentación completa para el despliegue y gestión de NetBox con Docker. + +## 📑 Índice + +### Inicio Rápido +- **[Home](Home)** - Esta página +- **[Generar Contraseñas](#generar-contraseñas)** - Antes de desplegar + +### Modos de Despliegue +- **[Traefik](Traefik)** - Proxy inverso con SSL automático +- **[NPM](NPM)** - Nginx Proxy Manager + +### Configuración y Uso +- **[Configuración Inicial](Configuración-Inicial)** - Primer acceso y setup +- **[Personalización](Personalización)** - LDAP, plugins, configuración avanzada +- **[Backup y Restauración](Backup-y-Restauración)** - Protege tus datos +- **[Actualización](Actualización)** - Mantén NetBox actualizado +- **[Solución de Problemas](Solución-de-Problemas)** - Diagnóstico y fixes + +--- + +## ¿Qué es NetBox? + +NetBox es una **solución IPAM (IP Address Management) y DCIM (Data Center Infrastructure Management)** de código abierto diseñada específicamente para equipos de red y data centers. + +### Características Principales + +- 📊 **IPAM Completo**: Gestión de IPs, VLANs, VRFs, prefijos +- 🖥️ **DCIM**: Inventario de racks, dispositivos, cables, conexiones +- 🔌 **Gestión de Circuitos**: Proveedores, circuitos, conexiones WAN +- 📝 **Documentación Rica**: Custom fields, tags, journaling +- 🔗 **API REST Completa**: Integración con sistemas externos +- 🔐 **Multi-tenancy**: Soporte para múltiples organizaciones +- 📈 **Reportes**: Visualización y exportación de datos +- 🔄 **Webhooks**: Automatización y notificaciones en tiempo real + +### Casos de Uso + +- **Gestión de IPs**: Planificación y asignación de direcciones IPv4/IPv6 +- **Inventario de Red**: Documentar switches, routers, firewalls +- **Gestión de Data Center**: Racks, PDUs, cables, patch panels +- **Documentación**: Single source of truth para infraestructura +- **Automatización**: Integración con Ansible, Terraform, scripts + +--- + +## Inicio Rápido + +### Requisitos + +- Docker Engine +- Portainer (recomendado) +- Red `proxy` creada +- PostgreSQL 18 y Redis (incluidos en el compose) + +### Generar Contraseñas + +**ANTES de desplegar**, genera 3 contraseñas seguras: + +```bash +# DB_PASSWORD (PostgreSQL) +openssl rand -base64 32 + +# REDIS_PASSWORD +openssl rand -base64 32 + +# SUPERUSER_PASSWORD (admin de NetBox) +openssl rand -base64 32 +``` + +> ⚠️ **Importante**: Si las contraseñas contienen caracteres especiales (`$`, `!`, etc.), usa comillas simples en el `.env`: +> ```env +> DB_PASSWORD='tu_password_con_$_especiales' +> ``` + +### Despliegue Básico + +1. **Crea el stack en Portainer** con Git Repository: + - URL: `https://git.ictiberia.com/groales/netbox` + - Compose path: `docker-compose.yml` + +2. **Añade variables de entorno**: + ```env + DB_PASSWORD=password_generado_1 + REDIS_PASSWORD=password_generado_2 + SUPERUSER_EMAIL=admin@example.com + SUPERUSER_PASSWORD=password_generado_3 + ALLOWED_HOST=* + ``` + +3. **Deploy** y espera 1-2 minutos (NetBox inicializa la BD) + +4. **Accede** y configura según tu proxy inverso: + - **[Traefik](Traefik)**: `https://netbox.tudominio.com` + - **[NPM](NPM)**: Configura Proxy Host primero + +--- + +## Arquitectura + +``` +┌─────────────────────────────────────────────────┐ +│ Traefik / NPM (Proxy) │ +│ HTTPS / SSL │ +└────────────────┬────────────────────────────────┘ + │ + ┌─────────▼──────────┐ + │ NetBox │ Puerto 8000 + │ (LinuxServer) │ + └─┬────────────────┬─┘ + │ │ + ┌────▼─────┐ ┌────▼──────┐ + │PostgreSQL│ │ Redis │ + │ 18 │ │ 7 │ + └──────────┘ └───────────┘ + (Base Datos) (Caché) +``` + +### Componentes + +- **NetBox**: Aplicación Django (puerto 8000) +- **PostgreSQL 18**: Base de datos principal +- **Redis 7**: Caché y mensajería +- **Proxy**: Traefik o NPM para HTTPS + +### Volúmenes + +- `netbox_config`: Configuración, media, scripts +- `netbox_db`: Base de datos PostgreSQL +- `netbox_redis`: Datos de Redis (caché) + +--- + +## Próximos Pasos + +1. **Elige tu modo de despliegue**: + - [Traefik](Traefik) - Recomendado para múltiples servicios + - [NPM](NPM) - Más simple para configurar + +2. **Configura NetBox**: + - [Configuración Inicial](Configuración-Inicial) - Primer acceso + - [Personalización](Personalización) - LDAP, plugins, etc. + +3. **Protege tus datos**: + - [Backup y Restauración](Backup-y-Restauración) - Automatiza backups + +4. **Mantén actualizado**: + - [Actualización](Actualización) - NetBox y PostgreSQL + +--- + +## Recursos Oficiales + +- [Documentación NetBox](https://docs.netbox.dev/) +- [LinuxServer NetBox](https://docs.linuxserver.io/images/docker-netbox) +- [Device Type Library](https://github.com/netbox-community/devicetype-library) +- [API Docs](https://demo.netbox.dev/api/docs/) +- [Plugins](https://github.com/netbox-community/netbox/wiki/Plugins) \ No newline at end of file diff --git a/NPM.md b/NPM.md new file mode 100644 index 0000000..207fb1b --- /dev/null +++ b/NPM.md @@ -0,0 +1,147 @@ +# Despliegue con Nginx Proxy Manager (NPM) + +NetBox detrás de NPM con certificado SSL de Let's Encrypt. + +## Requisitos Previos + +- ✅ NPM desplegado y accesible +- ✅ Red Docker `proxy` creada +- ✅ DNS apuntando al servidor + +--- + +## Pasos de Configuración + +### 1. Desplegar NetBox + +En Portainer, crea el stack **sin archivo override** (solo `docker-compose.yml`): + +**Variables de entorno**: +```env +DB_PASSWORD=password_generado_1 +REDIS_PASSWORD=password_generado_2 +SUPERUSER_EMAIL=admin@example.com +SUPERUSER_PASSWORD=password_generado_3 +ALLOWED_HOST=* +DB_NAME=netbox +DB_USER=netbox +``` + +> ⚠️ **No añadas** `DOMAIN_HOST` - Solo se usa con Traefik + +### 2. Configurar Proxy Host en NPM + +1. Accede a NPM (ej: `https://npm.tudominio.com`) +2. Ve a **Hosts** → **Proxy Hosts** → **Add Proxy Host** + +#### Pestaña Details + +- **Domain Names**: `netbox.tudominio.com` +- **Scheme**: `http` +- **Forward Hostname / IP**: `netbox` +- **Forward Port**: `8000` +- ✅ **Cache Assets**: Activado +- ✅ **Block Common Exploits**: Activado +- ✅ **Websockets Support**: Activado + +#### Pestaña SSL + +- **SSL Certificate**: `Request a new SSL Certificate` +- **Email**: tu@email.com +- ✅ **Force SSL**: Activado +- ✅ **HTTP/2 Support**: Activado +- ✅ **HSTS Enabled**: Activado (opcional) +- ✅ **HSTS Subdomains**: Activado (opcional) + +3. **Save** + +### 3. Verificar + +- Accede a `https://netbox.tudominio.com` +- Verifica el certificado SSL (candado verde) +- Login con `SUPERUSER_EMAIL` y `SUPERUSER_PASSWORD` + +--- + +## Configuración Avanzada (Opcional) + +### Custom Nginx Configuration + +Si necesitas ajustes específicos, ve a **Advanced** en el Proxy Host: + +```nginx +# Aumentar timeout para operaciones largas +proxy_read_timeout 300; +proxy_connect_timeout 300; +proxy_send_timeout 300; + +# Headers adicionales +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_set_header X-Forwarded-Host $host; + +# Buffer size para uploads grandes +client_max_body_size 100M; +``` + +--- + +## Solución de Problemas + +### 502 Bad Gateway + +**Causa**: NetBox no está accesible + +**Solución**: +```bash +# Verificar que NetBox está corriendo +docker ps | grep netbox + +# Ver logs +docker logs netbox + +# Verificar conexión desde NPM +docker exec -it npm ping netbox +``` + +### Certificado SSL no se genera + +**Soluciones**: +- Verificar que DNS apunta correctamente: `nslookup netbox.tudominio.com` +- Verificar puertos 80/443 abiertos +- Revisar logs de NPM +- Intentar con **Use a DNS Challenge** si tienes firewall + +### Error de permisos + +Si ves errores de permisos en NetBox: + +```bash +docker exec -it netbox chown -R abc:abc /config +docker restart netbox +``` + +--- + +## Comparación NPM vs Traefik + +| Característica | NPM | Traefik | +|----------------|-----|---------| +| Configuración | GUI (más fácil) | Código (más flexible) | +| SSL Automático | Manual por host | Automático | +| Múltiples servicios | Requiere configurar cada uno | Auto-discovery | +| Wildcards | Requiere DNS Challenge | Soportado | +| Middlewares | Limitados | Extensos | + +**Recomendación**: +- **NPM**: Si tienes pocos servicios y prefieres GUI +- **Traefik**: Si gestionas muchos servicios y quieres automatización + +--- + +## Próximos Pasos + +1. **[Configuración Inicial](Configuración-Inicial)** - Setup de NetBox +2. **[Personalización](Personalización)** - LDAP, plugins +3. **[Backup](Backup-y-Restauración)** - Protege tus datos diff --git a/Personalización.md b/Personalización.md new file mode 100644 index 0000000..a7ecb26 --- /dev/null +++ b/Personalización.md @@ -0,0 +1,277 @@ +# Personalización + +Configuración avanzada de NetBox: LDAP, plugins, scripts y más. + +## Configuración de Archivos + +NetBox usa `/config/` para almacenar configuración personalizada. + +### Acceder a Configuración + +```bash +# Entrar al contenedor +docker exec -it netbox bash + +# Navegar a config +cd /config + +# Ver archivos +ls -la +``` + +**Archivos importantes**: +- `configuration.py` - Configuración principal +- `ldap_config.py` - Autenticación LDAP (si usas LDAP) +- `plugins/` - Directorio de plugins +- `reports/` - Scripts de reportes personalizados +- `scripts/` - Scripts ejecutables desde UI + +--- + +## Autenticación LDAP + +### Configurar LDAP + +Edita `/config/ldap_config.py`: + +```python +import ldap +from django_auth_ldap.config import LDAPSearch, GroupOfNamesType + +# Servidor LDAP +AUTH_LDAP_SERVER_URI = "ldap://ldap.example.com" + +# Credenciales para bind +AUTH_LDAP_BIND_DN = "CN=netbox,OU=Services,DC=example,DC=com" +AUTH_LDAP_BIND_PASSWORD = "password" + +# Búsqueda de usuarios +AUTH_LDAP_USER_SEARCH = LDAPSearch( + "OU=Users,DC=example,DC=com", + ldap.SCOPE_SUBTREE, + "(sAMAccountName=%(user)s)" +) + +# Mapeo de atributos +AUTH_LDAP_USER_ATTR_MAP = { + "first_name": "givenName", + "last_name": "sn", + "email": "mail" +} + +# Grupos +AUTH_LDAP_GROUP_SEARCH = LDAPSearch( + "OU=Groups,DC=example,DC=com", + ldap.SCOPE_SUBTREE, + "(objectClass=group)" +) + +AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() + +# Permisos basados en grupos +AUTH_LDAP_USER_FLAGS_BY_GROUP = { + "is_staff": "CN=NetBox Admins,OU=Groups,DC=example,DC=com", + "is_superuser": "CN=NetBox Superusers,OU=Groups,DC=example,DC=com" +} + +# Sincronización automática +AUTH_LDAP_ALWAYS_UPDATE_USER = True +AUTH_LDAP_FIND_GROUP_PERMS = True +AUTH_LDAP_MIRROR_GROUPS = True +``` + +Reinicia NetBox: `docker restart netbox` + +--- + +## Plugins + +### Instalar Plugin + +```bash +# Ejemplo: NetBox Topology Views +docker exec -it netbox bash +pip install netbox-topology-views + +# Editar configuration.py +nano /config/configuration.py + +# Añadir a PLUGINS +PLUGINS = ['netbox_topology_views'] + +# Configuración específica del plugin (opcional) +PLUGINS_CONFIG = { + 'netbox_topology_views': { + 'static_image_directory': '/opt/netbox/netbox/media/topology_views' + } +} + +# Salir y reiniciar +exit +docker restart netbox +``` + +### Plugins Recomendados + +| Plugin | Descripción | +|--------|-------------| +| [netbox-topology-views](https://github.com/mattieserver/netbox-topology-views) | Visualización de topología de red | +| [netbox-secrets](https://github.com/Onemind-Services-LLC/netbox-secrets) | Gestión segura de credenciales | +| [netbox-bgp](https://github.com/k01ek/netbox-bgp) | Gestión de sesiones BGP | +| [netbox-documents](https://github.com/jasonyy2022/netbox-documents) | Adjuntar documentos | + +--- + +## Scripts Personalizados + +### Crear Script + +```bash +# Crear script en /config/scripts/ +docker exec -it netbox bash +nano /config/scripts/example_script.py +``` + +**Ejemplo de script**: + +```python +from dcim.models import Device +from extras.scripts import Script + +class DeviceAudit(Script): + class Meta: + name = "Device Audit" + description = "Genera reporte de dispositivos sin IP asignada" + + def run(self, data, commit): + devices_without_ip = Device.objects.filter( + primary_ip4__isnull=True, + primary_ip6__isnull=True + ) + + self.log_info(f"Dispositivos sin IP: {devices_without_ip.count()}") + + for device in devices_without_ip: + self.log_warning(f" - {device.name} ({device.site.name})") + + return f"Auditados {devices_without_ip.count()} dispositivos" +``` + +El script aparecerá en **Scripts** en la UI de NetBox. + +--- + +## Configuración Avanzada + +### configuration.py + +Opciones comunes en `/config/configuration.py`: + +```python +# Banner personalizado +BANNER_TOP = 'NetBox Producción - ICT Iberia' +BANNER_BOTTOM = '' +BANNER_LOGIN = 'Acceso Restringido - Solo Personal Autorizado' + +# Paginación +PAGINATE_COUNT = 50 +MAX_PAGE_SIZE = 1000 + +# Preferencias de sesión +LOGIN_REQUIRED = True +SESSION_COOKIE_AGE = 1209600 # 2 semanas + +# Timeout de cambios +CHANGELOG_RETENTION = 90 # días + +# Enforcement de nombres únicos +ENFORCE_GLOBAL_UNIQUE = True + +# Webhooks y jobs +QUEUE_NAMES = ['default', 'high', 'low'] + +# Métricas +METRICS_ENABLED = True + +# GraphQL +GRAPHQL_ENABLED = True +``` + +### Personalizar Plantillas + +```bash +# Crear override de plantilla +docker exec -it netbox mkdir -p /config/templates/dcim/device +docker exec -it netbox cp /app/netbox/templates/dcim/device/base.html /config/templates/dcim/device/ +``` + +Edita `/config/templates/dcim/device/base.html` para personalizar la UI. + +--- + +## Integración con Herramientas + +### Ansible + +```yaml +- name: Get devices from NetBox + hosts: localhost + tasks: + - name: Query NetBox API + uri: + url: "https://netbox.example.com/api/dcim/devices/" + headers: + Authorization: "Token {{ netbox_token }}" + return_content: yes + register: devices + + - name: Show devices + debug: + var: devices.json.results +``` + +### Terraform + +```hcl +provider "netbox" { + server_url = "https://netbox.example.com" + api_token = var.netbox_token +} + +resource "netbox_prefix" "example" { + prefix = "10.0.0.0/24" + status = "active" + description = "Example prefix" +} +``` + +### Python + +```python +import pynetbox + +nb = pynetbox.api( + 'https://netbox.example.com', + token='tu_token_aqui' +) + +# Obtener dispositivos +devices = nb.dcim.devices.all() +for device in devices: + print(f"{device.name} - {device.primary_ip}") + +# Crear IP +new_ip = nb.ipam.ip_addresses.create( + address='192.168.1.100/24', + status='active', + dns_name='server.example.com' +) +``` + +--- + +## Próximos Pasos + +1. **[Backup](Backup-y-Restauración)** - Protege tu configuración +2. **[API Docs](https://netbox.example.com/api/docs/)** - Explora la API +3. **[Plugins Wiki](https://github.com/netbox-community/netbox/wiki/Plugins)** - Más plugins diff --git a/Solución-de-Problemas.md b/Solución-de-Problemas.md new file mode 100644 index 0000000..c022a10 --- /dev/null +++ b/Solución-de-Problemas.md @@ -0,0 +1,402 @@ +# Solución de Problemas + +Diagnóstico y resolución de problemas comunes en NetBox. + +## Diagnóstico General + +### Ver Logs + +```bash +# Logs de NetBox +docker logs netbox --tail 100 -f + +# Logs de PostgreSQL +docker logs netbox-db --tail 50 + +# Logs de Redis +docker logs netbox-redis --tail 50 + +# Logs del stack completo +docker compose logs -f +``` + +### Verificar Estado + +```bash +# Estado de contenedores +docker ps -a | grep netbox + +# Uso de recursos +docker stats netbox netbox-db netbox-redis --no-stream + +# Redes +docker network inspect netbox-internal +docker network inspect proxy +``` + +--- + +## Problemas Comunes + +### NetBox No Inicia + +**Síntomas**: Contenedor se reinicia constantemente + +**Diagnóstico**: +```bash +docker logs netbox | grep -i error +docker logs netbox | grep -i fatal +``` + +**Causas comunes**: + +1. **PostgreSQL no está listo** + ```bash + docker logs netbox-db + docker exec netbox-db pg_isready -U netbox + ``` + **Solución**: Esperar o reiniciar PostgreSQL + ```bash + docker restart netbox-db + sleep 10 + docker restart netbox + ``` + +2. **Redis no accesible** + ```bash + docker exec netbox-redis redis-cli --pass "PASSWORD" ping + ``` + **Solución**: Verificar REDIS_PASSWORD en .env + +3. **Permisos incorrectos** + ```bash + docker exec netbox ls -la /config + ``` + **Solución**: + ```bash + docker run --rm -v netbox_config:/config alpine chown -R 1000:1000 /config + docker restart netbox + ``` + +### Error de Conexión a Base de Datos + +**Síntomas**: +``` +could not connect to server: Connection refused +FATAL: password authentication failed +``` + +**Soluciones**: + +```bash +# Verificar que PostgreSQL está corriendo +docker ps | grep netbox-db + +# Verificar password en .env +cat .env | grep DB_PASSWORD + +# Verificar conexión desde NetBox +docker exec netbox ping netbox-db + +# Resetear conexión +docker restart netbox-db +sleep 10 +docker restart netbox +``` + +### Error 502 Bad Gateway (NPM/Traefik) + +**Síntomas**: Proxy no puede conectar con NetBox + +**Diagnóstico**: +```bash +# Verificar que NetBox está corriendo +docker ps | grep netbox + +# Verificar puerto 8000 +docker exec netbox netstat -tlnp | grep 8000 + +# Verificar desde proxy +docker exec npm ping netbox +``` + +**Soluciones**: +- Verificar que NetBox está en red `proxy` +- Verificar que el contenedor se llama `netbox` +- Reiniciar NetBox: `docker restart netbox` + +### Lentitud Extrema + +**Diagnóstico**: +```bash +# Ver uso de CPU/RAM +docker stats netbox netbox-db netbox-redis + +# Ver queries lentas en PostgreSQL +docker exec netbox-db psql -U netbox -c "SELECT query, calls, total_exec_time FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;" +``` + +**Soluciones**: + +1. **Limpiar caché de Redis** + ```bash + docker exec netbox-redis redis-cli --pass "PASSWORD" FLUSHALL + docker restart netbox + ``` + +2. **Optimizar PostgreSQL** + ```bash + docker exec netbox-db psql -U netbox -c "VACUUM ANALYZE;" + docker exec netbox-db psql -U netbox -c "REINDEX DATABASE netbox;" + ``` + +3. **Incrementar recursos** (editar compose): + ```yaml + services: + netbox: + deploy: + resources: + limits: + memory: 2G + reservations: + memory: 1G + ``` + +### Error de Migración de Base de Datos + +**Síntomas**: +``` +django.db.migrations.exceptions.InconsistentMigrationHistory +``` + +**Solución**: +```bash +# Ver migraciones aplicadas +docker exec netbox python /app/netbox/manage.py showmigrations + +# Aplicar migraciones faltantes +docker exec netbox python /app/netbox/manage.py migrate + +# Si persiste, forzar +docker exec netbox python /app/netbox/manage.py migrate --fake +``` + +### Certificado SSL no Funciona + +**Síntomas**: Certificado inválido o HTTPS no funciona + +**Soluciones**: + +**Con Traefik**: +```bash +# Ver logs de Traefik +docker logs traefik | grep -i acme +docker logs traefik | grep netbox + +# Verificar DNS +nslookup netbox.tudominio.com + +# Forzar renovación +docker exec traefik rm /letsencrypt/acme.json +docker restart traefik +``` + +**Con NPM**: +- Verificar que DNS apunta correctamente +- Intentar con DNS Challenge si 80/443 bloqueados +- Regenerar certificado en NPM UI + +### Plugin No Funciona + +**Diagnóstico**: +```bash +# Ver plugins instalados +docker exec netbox pip list | grep netbox + +# Ver logs de plugin +docker logs netbox | grep -i plugin +``` + +**Soluciones**: +```bash +# Reinstalar plugin +docker exec netbox pip install --force-reinstall netbox-plugin-name + +# Verificar configuration.py +docker exec netbox cat /config/configuration.py | grep PLUGINS + +# Reiniciar +docker restart netbox +``` + +--- + +## Comandos de Emergencia + +### Reiniciar Todo + +```bash +docker restart netbox netbox-redis netbox-db +``` + +### Recrear NetBox (Mantiene Datos) + +```bash +docker stop netbox +docker rm netbox +docker compose up -d netbox +``` + +### Limpiar y Reiniciar + +```bash +# CUIDADO: Pierde caché y sesiones +docker stop netbox netbox-redis +docker rm netbox-redis +docker volume rm netbox_redis +docker compose up -d netbox-redis +sleep 5 +docker start netbox +``` + +### Acceso de Emergencia a Django Shell + +```bash +# Shell de Django +docker exec -it netbox python /app/netbox/manage.py shell + +# Ejemplo: crear superusuario +>>> from django.contrib.auth import get_user_model +>>> User = get_user_model() +>>> User.objects.create_superuser('admin', 'admin@example.com', 'password') +``` + +### Resetear Password de Admin + +```bash +docker exec -it netbox python /app/netbox/manage.py changepassword admin +``` + +### Reconstruir Índices de Búsqueda + +```bash +docker exec netbox python /app/netbox/manage.py reindex --lazy +``` + +### Limpiar Sesiones Antiguas + +```bash +docker exec netbox python /app/netbox/manage.py clearsessions +``` + +--- + +## Recuperación de Desastres + +### NetBox Corrupto - Restaurar desde Backup + +```bash +# 1. Detener todo +docker stop netbox netbox-redis netbox-db + +# 2. Eliminar volúmenes corruptos +docker volume rm netbox_db netbox_config + +# 3. Recrear volúmenes +docker volume create netbox_db +docker volume create netbox_config + +# 4. Iniciar PostgreSQL +docker start netbox-db +sleep 10 + +# 5. Restaurar BD +gunzip < /backups/netbox/netbox-backup-FECHA.sql.gz | docker exec -i netbox-db psql -U netbox netbox + +# 6. Restaurar config +docker run --rm -v netbox_config:/restore -v /backups/netbox:/source alpine tar xzf /source/netbox-config-FECHA.tar.gz -C /restore + +# 7. Iniciar todo +docker start netbox-redis +sleep 5 +docker start netbox +``` + +### PostgreSQL Corrupto + +```bash +# Intentar reparar +docker exec netbox-db pg_resetwal /var/lib/postgresql/data + +# Si falla, restaurar desde backup +docker stop netbox-db +docker volume rm netbox_db +docker volume create netbox_db +docker start netbox-db +sleep 10 +cat netbox-backup.sql | docker exec -i netbox-db psql -U netbox netbox +``` + +--- + +## Obtener Ayuda + +### Información del Sistema + +```bash +# Versión de NetBox +docker exec netbox python /app/netbox/manage.py version + +# Versión de Python +docker exec netbox python --version + +# Versión de PostgreSQL +docker exec netbox-db psql --version + +# Variables de entorno +docker exec netbox env | grep -E "DB_|REDIS_|SUPER" + +# Compose usado +docker inspect netbox | grep -A 20 Labels +``` + +### Recursos Oficiales + +- [NetBox Discussions](https://github.com/netbox-community/netbox/discussions) +- [NetBox Slack](https://netdev.chat/) +- [LinuxServer Support](https://discourse.linuxserver.io/) +- [Stack Overflow](https://stackoverflow.com/questions/tagged/netbox) + +--- + +## Prevención + +### Monitorización + +```bash +# Script de health check +#!/bin/bash +if docker exec netbox curl -f http://localhost:8000/api/ > /dev/null 2>&1; then + echo "✓ NetBox OK" +else + echo "✗ NetBox DOWN" + docker logs netbox --tail 50 +fi +``` + +### Alertas + +Configura alertas en tu sistema de monitorización (Prometheus, Zabbix, etc.): + +- CPU > 80% +- RAM > 90% +- Disco > 85% +- NetBox no responde + +--- + +## Próximos Pasos + +1. **[Backup](Backup-y-Restauración)** - Automatiza backups para prevenir desastres +2. **[Actualización](Actualización)** - Mantén NetBox actualizado +3. **[Comunidad](https://github.com/netbox-community/netbox/discussions)** - Pregunta si no encuentras solución diff --git a/Traefik.md b/Traefik.md new file mode 100644 index 0000000..9154975 --- /dev/null +++ b/Traefik.md @@ -0,0 +1,262 @@ +# Despliegue con Traefik + +NetBox detrás de Traefik con SSL automático vía Let's Encrypt. + +## Requisitos Previos + +- ✅ Stack de Traefik desplegado y funcionando +- ✅ Red Docker `proxy` creada +- ✅ DNS apuntando al servidor (registro A para tu dominio) +- ✅ Puertos 80 y 443 accesibles desde internet + +--- + +## Configuración + +### 1. Preparar Variables de Entorno + +En Portainer, al crear el stack desde Git Repository, añade estas variables: + +```env +# Contraseñas (generadas previamente) +DB_PASSWORD=tu_password_generado_1 +REDIS_PASSWORD=tu_password_generado_2 +SUPERUSER_PASSWORD=tu_password_generado_3 + +# Superusuario de NetBox +SUPERUSER_EMAIL=admin@tudominio.com + +# Host permitido +ALLOWED_HOST=* + +# Base de datos (valores por defecto) +DB_NAME=netbox +DB_USER=netbox + +# ⚠️ IMPORTANTE para Traefik +DOMAIN_HOST=netbox.tudominio.com +``` + +### 2. Subir Archivo Override + +En Portainer, en la sección **Additional files**: + +1. Click en **Add file** +2. **Path**: `docker-compose.override.traefik.yml` +3. **Content**: Pega el contenido de `docker-compose.override.traefik.yml.example` + +```yaml +services: + netbox: + labels: + # Habilitar Traefik + - traefik.enable=true + + # Router HTTP (redirige a HTTPS) + - traefik.http.routers.netbox-http.rule=Host(`${DOMAIN_HOST}`) + - traefik.http.routers.netbox-http.entrypoints=web + - traefik.http.routers.netbox-http.middlewares=redirect-to-https + + # Router HTTPS + - traefik.http.routers.netbox.rule=Host(`${DOMAIN_HOST}`) + - traefik.http.routers.netbox.entrypoints=websecure + - traefik.http.routers.netbox.tls=true + - traefik.http.routers.netbox.tls.certresolver=letsencrypt + - traefik.http.routers.netbox.service=netbox-svc + - traefik.http.services.netbox-svc.loadbalancer.server.port=8000 + + # Redirect middleware + - traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https + - traefik.http.middlewares.redirect-to-https.redirectscheme.permanent=true +``` + +### 3. Deploy + +1. Click en **Deploy the stack** +2. Espera 1-2 minutos mientras NetBox inicializa +3. Verifica logs: `docker logs netbox -f` + +### 4. Verificar + +```bash +# Ver logs de NetBox +docker logs netbox --tail 50 + +# Verificar que Traefik detectó NetBox +docker logs traefik | grep netbox + +# Verificar certificado SSL +curl -I https://netbox.tudominio.com +``` + +--- + +## Compose Completo con Traefik + +Ejemplo completo si despliegas desde **Web editor**: + +```yaml +services: + netbox: + container_name: netbox + image: lscr.io/linuxserver/netbox:latest + restart: unless-stopped + environment: + PUID: 1000 + PGID: 1000 + TZ: Europe/Madrid + SUPERUSER_EMAIL: ${SUPERUSER_EMAIL} + SUPERUSER_PASSWORD: ${SUPERUSER_PASSWORD} + ALLOWED_HOST: ${ALLOWED_HOST} + DB_NAME: ${DB_NAME:-netbox} + DB_USER: ${DB_USER:-netbox} + DB_PASSWORD: ${DB_PASSWORD} + DB_HOST: netbox-db + DB_PORT: 5432 + REDIS_HOST: netbox-redis + REDIS_PORT: 6379 + REDIS_PASSWORD: ${REDIS_PASSWORD} + volumes: + - netbox_config:/config + networks: + - proxy + - netbox-internal + depends_on: + - netbox-db + - netbox-redis + labels: + - traefik.enable=true + - traefik.http.routers.netbox-http.rule=Host(`netbox.tudominio.com`) + - traefik.http.routers.netbox-http.entrypoints=web + - traefik.http.routers.netbox-http.middlewares=redirect-to-https + - traefik.http.routers.netbox.rule=Host(`netbox.tudominio.com`) + - traefik.http.routers.netbox.entrypoints=websecure + - traefik.http.routers.netbox.tls=true + - traefik.http.routers.netbox.tls.certresolver=letsencrypt + - traefik.http.routers.netbox.service=netbox-svc + - traefik.http.services.netbox-svc.loadbalancer.server.port=8000 + - traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https + - traefik.http.middlewares.redirect-to-https.redirectscheme.permanent=true + + netbox-db: + container_name: netbox-db + image: postgres:18-alpine + restart: unless-stopped + environment: + POSTGRES_DB: ${DB_NAME:-netbox} + POSTGRES_USER: ${DB_USER:-netbox} + POSTGRES_PASSWORD: ${DB_PASSWORD} + volumes: + - netbox_db:/var/lib/postgresql + networks: + - netbox-internal + + netbox-redis: + container_name: netbox-redis + image: redis:7-alpine + restart: unless-stopped + command: redis-server --requirepass ${REDIS_PASSWORD} + volumes: + - netbox_redis:/data + networks: + - netbox-internal + +volumes: + netbox_config: + name: netbox_config + netbox_db: + name: netbox_db + netbox_redis: + name: netbox_redis + +networks: + proxy: + external: true + netbox-internal: + name: netbox-internal +``` + +--- + +## Solución de Problemas + +### Traefik no detecta NetBox + +**Verificar**: +```bash +# Labels del contenedor +docker inspect netbox | grep -A 20 Labels + +# Redes del contenedor +docker inspect netbox | grep -A 10 Networks + +# Logs de Traefik +docker logs traefik | grep netbox +``` + +**Solución**: +- Verificar que NetBox está en la red `proxy` +- Verificar variable `DOMAIN_HOST` en env +- Reiniciar Traefik: `docker restart traefik` + +### Error de certificado SSL + +**Síntomas**: `NET::ERR_CERT_AUTHORITY_INVALID` + +**Solución**: +```bash +# Verificar logs de Traefik +docker logs traefik | grep -i acme + +# Verificar que el DNS apunta correctamente +nslookup netbox.tudominio.com + +# Forzar renovación de certificado +docker exec traefik rm /letsencrypt/acme.json +docker restart traefik +``` + +### Redirect loop + +**Síntomas**: La página recarga infinitamente + +**Solución**: +- Verificar que `ALLOWED_HOST` incluye tu dominio o está en `*` +- Comprobar configuración de Traefik (entrypoints) + +--- + +## Configuración Avanzada + +### Headers de Seguridad + +Añade a los labels de Traefik: + +```yaml +- traefik.http.middlewares.netbox-headers.headers.sslredirect=true +- traefik.http.middlewares.netbox-headers.headers.stsincludesubdomains=true +- traefik.http.middlewares.netbox-headers.headers.stspreload=true +- traefik.http.middlewares.netbox-headers.headers.stsseconds=31536000 +- traefik.http.routers.netbox.middlewares=netbox-headers +``` + +### Autenticación Básica (opcional) + +Si quieres protección adicional antes de acceder a NetBox: + +```bash +# Generar usuario:password +htpasswd -nb admin password + +# Añadir middleware +- traefik.http.middlewares.netbox-auth.basicauth.users=admin:$$apr1$$... +- traefik.http.routers.netbox.middlewares=netbox-auth +``` + +--- + +## Próximos Pasos + +1. **[Configuración Inicial](Configuración-Inicial)** - Primer acceso y setup +2. **[Personalización](Personalización)** - Configurar LDAP, plugins +3. **[Backup](Backup-y-Restauración)** - Automatiza backups diff --git a/_Sidebar.md b/_Sidebar.md new file mode 100644 index 0000000..c139cb9 --- /dev/null +++ b/_Sidebar.md @@ -0,0 +1,17 @@ +## NetBox Wiki + +### 🚀 Inicio +- [Home](Home) + +### 📦 Despliegue +- [Traefik](Traefik) +- [NPM](NPM) + +### ⚙️ Configuración +- [Configuración Inicial](Configuración-Inicial) +- [Personalización](Personalización) + +### 💾 Mantenimiento +- [Backup y Restauración](Backup-y-Restauración) +- [Actualización](Actualización) +- [Solución de Problemas](Solución-de-Problemas)