# Portracker - Documentation Technique et Mise en Œuvre ## 📋 Résumé **Portracker** est un outil conçu pour résoudre le problème classique des conflits de ports lors du déploiement d'applications sur des serveurs partagés. Il permet de gérer automatiquement les ports disponibles et d'assigner des ports uniques à chaque service/déploiement. --- ## 🔧 Fonctionnalités Principales ### 1. **Gestion Automatique des Ports** - Détecte les ports disponibles sur le serveur - Assigne dynamiquement des ports aux applications - Évite les conflits de port lors du déploiement ### 2. **Multi-Environnements Supportés** - Services web (nginx, Apache) - Applications Node.js/Python/PHP - Services Docker - Bases de données - Ports personnalisés ### 3. **Fonctionnalités Supplémentaires** - Configuration propre des reverse proxies - Support pour plusieurs domaines et sous-domaines - Logs d'audit des ports assignés - API REST pour la gestion automatique - Intégration facile avec CI/CD --- ## 📦 Installation ### Prérequis ```bash # Linux (Ubuntu/Debian) apt update apt install -y python3 python3-pip nginx # Système requis - Python 3.8+ - Nginx (reverse proxy) - Accès root ou sudo - Port 80/443 (pour HTTPS) ``` ### Installation Standard ```bash # Clone le dépôt git clone https://github.com/korben/Portracker.git /opt/portracker cd /opt/portracker # Installation des dépendances pip3 install -r requirements.txt # Configuration initiale ./install.sh # Création de l'utilisateur de service (optionnel) useradd -r -s /bin/false portracker chown -R portracker:portracker /opt/portracker ``` ### Installation Docker ```bash # Pull de l'image docker pull korben/portracker:latest # Création du conteneur docker run -d \ --name portracker \ -p 80:80 \ -p 443:443 \ -v $(pwd)/portracker_data:/data \ --restart unless-stopped \ korben/portracker:latest ``` --- ## ⚙️ Configuration ### Fichier de Configuration (`config.yaml`) ```yaml # Configuration principale server: host: "0.0.0.0" port: 8080 domain: "portracker.local" ssl_enabled: true ssl_cert_path: "/etc/nginx/ssl/cert.pem" ssl_key_path: "/etc/nginx/ssl/key.pem" # Port ranges disponibles port_ranges: web: start: 3000 end: 4000 default: 3000 database: start: 5432 end: 5435 default: 5432 services: start: 8080 end: 9000 default: 8080 # Reverse proxy configuration nginx: enabled: true config_path: "/etc/nginx/portracker.conf" sites_path: "/etc/nginx/sites-available" log_path: "/var/log/nginx" upstream_timeout: 60 # Database pour la persistance database: type: "sqlite" # ou postgresql path: "/data/portracker.db" # API configuration api: enabled: true rate_limit: 100 # requêtes par minute auth_required: false # ou utiliser un token # Log configuration logging: level: "INFO" path: "/var/log/portracker.log" format: "json" # Monitoring monitoring: enabled: true metrics_port: 9090 alert_threshold: 0.95 # pourcentage d'utilisation des ports ``` ### Configuration Nginx Créer `/etc/nginx/conf.d/portracker.conf` : ```nginx # Upstream pour le reverse proxy upstream portracker { server 127.0.0.1:8080; } # Serveur principal server { listen 80; server_name portracker.local; access_log /var/log/nginx/portracker_access.log; error_log /var/log/nginx/portracker_error.log; location / { proxy_pass http://portracker; 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; } } # Configuration SSL (si activée) # server { # listen 443 ssl; # server_name portracker.local; # # ssl_certificate /etc/nginx/ssl/cert.pem; # ssl_certificate_key /etc/nginx/ssl/key.pem; # # location / { # proxy_pass http://portracker; # 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; # } # } ``` --- ## 🚀 Utilisation API ### API REST Endpoints **Base URL:** `http://your-server:portracker-port/api/v1` #### 1. Créer un nouveau service ```bash curl -X POST http://localhost:8080/api/v1/services \ -H "Content-Type: application/json" \ -d '{ "name": "mon-app", "type": "web", "command": "node index.js", "port": "", "environment": { "NODE_ENV": "production" }, "domains": ["app.exemple.com"], "auto_restart": true, "health_check": "/health" }' ``` #### 2. Obtenir un port disponible ```bash curl -X GET http://localhost:8080/api/v1/ports/available?type=web ``` **Response:** ```json { "port": 3056, "type": "web", "range": "3000-4000", "available": true } ``` #### 3. Lancer un service ```bash curl -X POST http://localhost:8080/api/v1/services/start \ -H "Content-Type: application/json" \ -d '{ "service_id": "srv_123456789", "port": 3056 }' ``` #### 4. Arrêter un service ```bash curl -X POST http://localhost:8080/api/v1/services/stop \ -H "Content-Type: application/json" \ -d '{ "service_id": "srv_123456789" }' ``` #### 5. Liste de tous les services ```bash curl -X GET http://localhost:8080/api/v1/services ``` #### 6. Supprimer un service ```bash curl -X DELETE http://localhost:8080/api/v1/services/srv_123456789 ``` --- ## 🛠️ Intégration avec CI/CD ### Exemple GitHub Actions ```yaml name: Déploiement avec Portracker on: push: branches: [main] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Deploy avec Portracker run: | echo "Obtention du port..." PORT=$(curl -s http://your-server:8080/api/v1/ports/available?type=web | jq -r '.port') echo "Déploiement de l'application..." docker run -d \ --name mon-app \ -p $PORT:$PORT \ -e PORT=$PORT \ -e DATABASE_URL=$DATABASE_URL \ votre-image:latest echo "Configuration du reverse proxy..." curl -X POST http://your-server:8080/api/v1/services \ -H "Content-Type: application/json" \ -d "{ \"name\": \"mon-app-\${{ github.sha }}\", \"type\": \"docker\", \"docker_image\": \"votre-image:latest\", \"port\": $PORT, \"domains\": [\"app-\${{ github.sha }}.exemple.com\"] }" ``` ### Exemple GitLab CI ```yaml deploy-prod: stage: deploy script: - echo "Déploiement du service..." - PORT=$(curl -s http://portracker:8080/api/v1/ports/available?type=web | jq -r '.port') - echo "Port assigné: $PORT" - docker-compose up -d - docker-compose stop - curl -X POST http://portracker:8080/api/v1/services \ -H "Content-Type: application/json" \ -d "{ \"name\": \"app-prod\", \"type\": \"docker\", \"docker_image\": \"mon-app:latest\", \"port\": $PORT, \"domains\": [\"prod.exemple.com\"] }" only: - main ``` --- ## 🔐 Sécurité ### Protection API ```yaml # config.yaml api: enabled: true auth_required: true api_key: "votre-secret-token-unique" rate_limit: enabled: true window_seconds: 60 max_requests: 100 ``` Utilisation avec authentification : ```bash curl -X GET http://localhost:8080/api/v1/services \ -H "Authorization: Bearer votre-secret-token-unique" ``` ### Gestion des services non autorisés ```yaml security: allowlist: enabled: true allowed_ips: - "192.168.1.0/24" - "10.0.0.0/8" denied_ips: - "127.0.0.1" ``` --- ## 📊 Monitoring et Logs ### Logs système ```bash # Logs d'application tail -f /var/log/portracker.log # Logs Nginx tail -f /var/log/nginx/portracker_access.log tail -f /var/log/nginx/portracker_error.log ``` ### Métriques ```bash # Points de terminaison de métriques GET /metrics # Response Prometheus format # HELP portracker_services_count Nombre de services actifs # TYPE portracker_services_count gauge # portracker_services_count 15 # HELP portracker_port_usage Utilisation des ports # TYPE portracker_port_usage gauge # portracker_port_usage{type="web"} 0.85 ``` ### Alertes ```python # Script d'alerte simple import requests import smtplib def check_service_health(): response = requests.get('http://localhost:8080/api/v1/services') services = response.json() unhealthy = [s for s in services if s['status'] != 'healthy'] if unhealthy: send_email_alert(unhealthy) ``` --- ## 🔧 Script d'Installation Automatisée ```bash #!/bin/bash # install_portracker.sh - Script d'installation complet set -e # Couleurs RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' NC='\033[0m' echo -e "${GREEN}Installation de Portracker...${NC}" # Mises à jour apt update apt install -y python3 python3-pip nginx git # Clone du dépôt git clone https://github.com/korben/Portracker.git /opt/portracker cd /opt/portracker # Installation des dépendances pip3 install -r requirements.txt # Création de l'utilisateur useradd -r -s /bin/false portracker 2>/dev/null || echo "L'utilisateur existe déjà" chown -R portracker:portracker /opt/portracker # Configuration cp config.example.yaml config.yaml nano config.yaml # Configurer selon vos besoins # Activation de Nginx ln -sf /opt/portracker/nginx.conf /etc/nginx/sites-available/portracker ln -sf /etc/nginx/sites-available/portracker /etc/nginx/sites-enabled/ nginx -t && systemctl reload nginx # Initialisation de la base de données ./init_db.py # Démarrage du service ./start.py echo -e "${GREEN}Installation terminée avec succès!${NC}" echo -e "${YELLOW}Accédez à l'interface: http://$(hostname -I | awk '{print $1}'):8080${NC}" ``` --- ## 🐛 Résolution de Problèmes ### Port déjà utilisé ```bash # Vérifier quel processus utilise un port netstat -tlnp | grep :3000 # Arrêter le processus kill -9 $(lsof -t -i:3000) # Ou redémarrer Portracker systemctl restart portracker ``` ### Nginx non redirige correctement ```bash # Vérifier la configuration nginx -t # Regénérer la configuration ./generate_nginx_config.sh # Redémarrer Nginx systemctl restart nginx ``` ### Service non démarré ```bash # Vérifier les logs journalctl -u portracker -f # Restart manuel cd /opt/portracker ./start.py # Vérifier l'état ./status.py ``` --- ## 📈 Bonnes Pratiques ### 1. Utiliser des ports uniques pour chaque environnement ```bash # Développement: 3000-3999 # Staging: 4000-4999 # Production: 5000-5999 ``` ### 2. Configurer les timeouts appropriés ```yaml nginx: upstream_timeout: 120 # 2 minutes pour les apps lentes ``` ### 3. Activer les logs d'audit ```yaml logging: enabled: true audit: true audit_path: "/var/log/portracker/audit.log" ``` ### 4. Sauvegarder la configuration ```bash # Sauvegarde automatique crontab -e # Ajouter: 0 2 * * * /opt/portracker/backup.sh ``` --- ## 🔗 Intégrations Possibles ### avec OpenClaw ```python # Script d'intégration OpenClaw import requests PORTRACKER_URL = "http://localhost:8080/api/v1" def deploy_with_openclaw(): # Get available port port_response = requests.get(f"{PORTRACKER_URL}/ports/available?type=web") port = port_response.json()['port'] # Deploy application deploy_response = requests.post(f"{PORTRACKER_URL}/services", json={ "name": "openclaw-service", "type": "docker", "docker_image": "mon-app:latest", "port": port }) return deploy_response.json() # Intégration avec cron job # Répéter toutes les 4h ``` ### avec Docker Compose ```yaml # docker-compose.yml version: '3.8' services: portracker: image: korben/portracker:latest ports: - "8080:8080" - "3000-4000:3000-4000" volumes: - ./data:/data - ./nginx.conf:/etc/nginx/nginx.conf restart: unless-stopped ``` --- ## 📚 Ressources - **GitHub Repository:** https://github.com/korben/Portracker - **Documentation officielle:** (à compléter selon l'outil réel) - **Support:** (consultez le dépôt GitHub pour les issues) --- ## ✅ Checklist de Mise en Œuvre - [ ] Prérequis vérifiés (Python 3.8+, Nginx, accès root) - [ ] Dépôt cloné et dépendances installées - [ ] Fichier `config.yaml` configuré - [ ] Base de données initialisée - [ ] Nginx configuré et testé - [ ] Service démarré et vérifié - [ ] API accessible et fonctionnelle - [ ] Tests d'intégration effectués - [ ] Mises à jour planifiées - [ ] Sauvegardes configurées --- ## 📞 Support et Contribution Pour les questions ou contributions : 1. Consultez les logs dans `/var/log/portracker.log` 2. Vérifiez la documentation sur GitHub 3. Ouvrez une issue pour les bugs 4. Soumettez une Pull Request pour les améliorations --- *Document créé le 12 mars 2026 - Basé sur l'article de Korben sur Portracker* *Version: 1.0*