From b2f04b6600b4a7f6fa223eff6b356867aad3b743 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Fri, 12 Dec 2025 23:40:34 +0100 Subject: [PATCH] Supporto Docker/Unraid: build, healthcheck, docs Aggiunti Dockerfile multi-stage, .dockerignore e docker-compose.yml per deployment containerizzato (con healthcheck, volumi persistenti, limiti risorse). Script di build per Linux/Mac e Windows. In Program.cs aggiunto endpoint /health e health checks per orchestrazione. Documentazione estesa: guide Unraid, quickstart Docker, workflow Git/DevOps, best practices su sicurezza, backup, monitoring. Progetto ora pronto per deploy e gestione professionale in ambienti Docker/Unraid. --- TradingBot/.dockerignore | 73 +++++ TradingBot/DOCKER_QUICKSTART.md | 141 +++++++++ TradingBot/Dockerfile | 54 ++++ TradingBot/GIT_WORKFLOW.md | 410 +++++++++++++++++++++++++ TradingBot/Program.cs | 11 +- TradingBot/README.md | 21 +- TradingBot/UNRAID_DEPLOYMENT.md | 517 ++++++++++++++++++++++++++++++++ TradingBot/build-docker.bat | 29 ++ TradingBot/build-docker.sh | 49 +++ TradingBot/docker-compose.yml | 52 ++++ 10 files changed, 1352 insertions(+), 5 deletions(-) create mode 100644 TradingBot/.dockerignore create mode 100644 TradingBot/DOCKER_QUICKSTART.md create mode 100644 TradingBot/Dockerfile create mode 100644 TradingBot/GIT_WORKFLOW.md create mode 100644 TradingBot/UNRAID_DEPLOYMENT.md create mode 100644 TradingBot/build-docker.bat create mode 100644 TradingBot/build-docker.sh create mode 100644 TradingBot/docker-compose.yml diff --git a/TradingBot/.dockerignore b/TradingBot/.dockerignore new file mode 100644 index 0000000..e91e8e7 --- /dev/null +++ b/TradingBot/.dockerignore @@ -0,0 +1,73 @@ +# Build artifacts +**/bin/ +**/obj/ +**/out/ + +# Visual Studio +.vs/ +.vscode/ +*.suo +*.user +*.userosscache +*.sln.docstates + +# Files +*.log +*.cache +*.swp +*~ + +# NuGet +*.nupkg +**/packages/* +!**/packages/build/ +*.nuget.props +*.nuget.targets +project.lock.json +project.fragment.lock.json +artifacts/ + +# Test results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* +*.trx +*.coverage +*.coveragexml + +# Node (se usato per build frontend) +node_modules/ +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# OS +.DS_Store +Thumbs.db + +# Documentation (opzionale - include se vuoi in produzione) +*.md +!README.md + +# Git +.git/ +.gitignore +.gitattributes + +# Docker +Dockerfile +docker-compose*.yml +.dockerignore + +# Temp files +*.tmp +*.temp +*.bak + +# Local settings +appsettings.Development.json +**/appsettings.local.json + +# IDE +.idea/ +*.swp +*.swo diff --git a/TradingBot/DOCKER_QUICKSTART.md b/TradingBot/DOCKER_QUICKSTART.md new file mode 100644 index 0000000..ed29e6f --- /dev/null +++ b/TradingBot/DOCKER_QUICKSTART.md @@ -0,0 +1,141 @@ +# ?? QUICK START - Docker Deployment + +## Per Sviluppo Locale + +### Windows +```powershell +# Build +.\build-docker.bat + +# Run +docker-compose up -d + +# Logs +docker-compose logs -f + +# Stop +docker-compose down +``` + +### Linux/Mac +```sh +# Build +chmod +x build-docker.sh +./build-docker.sh + +# Run +docker-compose up -d + +# Logs +docker-compose logs -f + +# Stop +docker-compose down +``` + +### Accesso +``` +http://localhost:8080 +``` + +--- + +## Per Unraid (via Portainer) + +### 1. Setup Git Repository +```sh +git add . +git commit -m "Docker ready" +git push origin main +``` + +### 2. Deploy su Portainer +1. Stacks ? Add stack +2. Name: `tradingbot` +3. Git Repository: `https://192.168.30.23/Alby96/Encelado` +4. Compose path: `TradingBot/docker-compose.yml` +5. Deploy + +### 3. Accesso +``` +http://[UNRAID-IP]:8080 +``` + +--- + +## Per Unraid (via SSH) + +```sh +# SSH +ssh root@[UNRAID-IP] + +# Clone +cd /mnt/user/appdata +git clone https://192.168.30.23/Alby96/Encelado.git tradingbot +cd tradingbot/TradingBot + +# Deploy +docker-compose up -d + +# Check +docker ps | grep tradingbot +``` + +--- + +## Comandi Utili + +```sh +# Status +docker ps + +# Logs +docker logs tradingbot -f + +# Restart +docker restart tradingbot + +# Update +git pull && docker-compose up -d --build + +# Remove +docker-compose down -v +``` + +--- + +## Environment Variables (opzionali) + +Crea file `.env`: +```env +TZ=Europe/Rome +ASPNETCORE_ENVIRONMENT=Production +TRADINGBOT_AUTOSTART=true +``` + +--- + +## Troubleshooting + +### Container non parte +```sh +docker logs tradingbot +``` + +### Porta gią usata +```sh +# Cambia porta in docker-compose.yml +ports: + - "8081:8080" +``` + +### Rebuild da zero +```sh +docker-compose down -v +docker-compose build --no-cache +docker-compose up -d +``` + +--- + +Documentazione completa: [UNRAID_DEPLOYMENT.md](UNRAID_DEPLOYMENT.md) diff --git a/TradingBot/Dockerfile b/TradingBot/Dockerfile new file mode 100644 index 0000000..857f3d2 --- /dev/null +++ b/TradingBot/Dockerfile @@ -0,0 +1,54 @@ +# Dockerfile per TradingBot - Multi-stage build ottimizzato +# Stage 1: Build +FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build +WORKDIR /src + +# Copy csproj e restore dipendenze (layer caching) +COPY ["TradingBot.csproj", "./"] +RUN dotnet restore "TradingBot.csproj" + +# Copy tutto il codice sorgente +COPY . . + +# Build in Release mode +RUN dotnet build "TradingBot.csproj" -c Release -o /app/build + +# Stage 2: Publish +FROM build AS publish +RUN dotnet publish "TradingBot.csproj" -c Release -o /app/publish /p:UseAppHost=false + +# Stage 3: Runtime +FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final +WORKDIR /app + +# Crea utente non-root per sicurezza +RUN useradd -m -u 1000 tradingbot && \ + chown -R tradingbot:tradingbot /app + +# Esponi porta +EXPOSE 8080 + +# Copy published app +COPY --from=publish /app/publish . + +# Crea directory per persistenza dati +RUN mkdir -p /app/data && \ + chown -R tradingbot:tradingbot /app/data + +# Volume per dati persistenti +VOLUME ["/app/data"] + +# Switch a utente non-root +USER tradingbot + +# Environment variables +ENV ASPNETCORE_URLS=http://+:8080 +ENV ASPNETCORE_ENVIRONMENT=Production +ENV DOTNET_RUNNING_IN_CONTAINER=true + +# Health check +HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ + CMD curl -f http://localhost:8080/health || exit 1 + +# Entry point +ENTRYPOINT ["dotnet", "TradingBot.dll"] diff --git a/TradingBot/GIT_WORKFLOW.md b/TradingBot/GIT_WORKFLOW.md new file mode 100644 index 0000000..f3ce446 --- /dev/null +++ b/TradingBot/GIT_WORKFLOW.md @@ -0,0 +1,410 @@ +# ?? WORKFLOW: Sviluppo ? Gitea ? Unraid + +## Flusso di Lavoro Completo + +``` +PC Sviluppo ? Git Commit ? Gitea Push ? Unraid Pull ? Docker Deploy +``` + +--- + +## ?? STEP BY STEP + +### 1. Sviluppo Locale (PC) + +```sh +# Lavora sul codice +code . + +# Test locale +dotnet run +# Oppure +docker-compose up + +# Verifica funzionamento +http://localhost:8080 +``` + +### 2. Commit e Push su Gitea + +```sh +# Status modifiche +git status + +# Stage files +git add . + +# Commit +git commit -m "Feature: Descrizione modifiche" + +# Push su Gitea +git push origin main +``` + +### 3. Deploy su Unraid + +#### Opzione A: Automatico (Portainer Webhook) + +**Setup iniziale** (una volta): +``` +1. Portainer ? Stacks ? tradingbot ? Webhooks +2. Create webhook +3. Copy URL + +4. Gitea ? Settings ? Webhooks ? Add Webhook +5. Paste URL +6. Trigger: Push events +7. Save +``` + +**Uso**: Ogni push su Gitea ? Auto-deploy su Unraid! + +#### Opzione B: Manuale (SSH) + +```sh +# SSH su Unraid +ssh root@[UNRAID-IP] + +# Vai nella directory +cd /mnt/user/appdata/tradingbot/TradingBot + +# Pull modifiche +git pull origin main + +# Rebuild e restart +docker-compose down +docker-compose build +docker-compose up -d +``` + +#### Opzione C: Script Automatico + +Crea `/root/scripts/deploy-tradingbot.sh`: + +```sh +#!/bin/bash +cd /mnt/user/appdata/tradingbot/TradingBot + +echo "?? Pulling latest changes..." +git pull origin main + +if [ $? -eq 0 ]; then + echo "?? Rebuilding container..." + docker-compose down + docker-compose build + docker-compose up -d + echo "? Deployment completed!" +else + echo "? Git pull failed!" + exit 1 +fi +``` + +Usa: +```sh +chmod +x /root/scripts/deploy-tradingbot.sh +/root/scripts/deploy-tradingbot.sh +``` + +--- + +## ?? WORKFLOW GIORNALIERO + +### Mattina - Modifiche + +```sh +# PC +git pull origin main # Sync +code . # Sviluppa +dotnet run # Test +``` + +### Pomeriggio - Deploy + +```sh +# PC +git add . +git commit -m "Daily improvements" +git push origin main + +# Unraid (se non auto-deploy) +ssh root@unraid +/root/scripts/deploy-tradingbot.sh +``` + +### Sera - Monitoring + +```sh +# Check logs +docker logs tradingbot -f + +# Check stats +docker stats tradingbot + +# Backup (opzionale) +/root/scripts/backup-tradingbot.sh +``` + +--- + +## ?? BRANCHING STRATEGY + +### Main Branch (Production) +```sh +# Solo codice stabile e testato +git checkout main +git pull origin main +``` + +### Development Branch +```sh +# Crea branch per nuove feature +git checkout -b feature/nome-feature + +# Sviluppa e testa +# ... + +# Merge in main quando pronto +git checkout main +git merge feature/nome-feature +git push origin main +``` + +### Hotfix +```sh +# Per fix urgenti +git checkout -b hotfix/descrizione +# Fix +git checkout main +git merge hotfix/descrizione +git push origin main +``` + +--- + +## ?? RELEASE VERSIONING + +### Tagging +```sh +# Tag versione +git tag -a v1.0.0 -m "Release v1.0.0" +git push origin v1.0.0 + +# Build con tag +docker build -t tradingbot:v1.0.0 . +docker tag tradingbot:v1.0.0 tradingbot:latest +``` + +### Rollback +```sh +# Lista tags +git tag -l + +# Checkout versione precedente +git checkout v0.9.0 + +# Deploy versione specifica +docker-compose down +docker-compose build +docker-compose up -d +``` + +--- + +## ?? BEST PRACTICES + +### 1. Non Committare Secrets +```sh +# .gitignore gią configurato per: +appsettings.Development.json +*.env +*.key +``` + +### 2. Test Prima di Push +```sh +# Sempre test locale prima +dotnet build +dotnet test # Se hai tests +docker-compose up # Test container +``` + +### 3. Commit Messages Descrittivi +```sh +# ? Buoni +git commit -m "Fix: Sidebar toggle button not working" +git commit -m "Feature: Add Docker support" +git commit -m "Docs: Update deployment guide" + +# ? Cattivi +git commit -m "fix" +git commit -m "update" +git commit -m "changes" +``` + +### 4. Pull Prima di Push +```sh +# Sempre sync prima +git pull origin main +# Risolvi conflitti se presenti +git push origin main +``` + +--- + +## ?? TROUBLESHOOTING + +### Conflitto Git +```sh +# Pull con conflitti +git pull origin main + +# Risolvi manualmente i file in conflitto +# Cerca <<<<<<< HEAD + +# Dopo risolto +git add . +git commit -m "Resolve merge conflicts" +git push origin main +``` + +### Push Rifiutato +```sh +# Se remote č avanti +git pull --rebase origin main +git push origin main +``` + +### Reset Completo (ATTENZIONE!) +```sh +# Solo in caso di emergenza +git fetch origin +git reset --hard origin/main +``` + +--- + +## ?? MONITORING WORKFLOW + +### Check Health +```sh +# Local +curl http://localhost:8080/health + +# Unraid +curl http://[UNRAID-IP]:8080/health +``` + +### View Logs +```sh +# Real-time +docker logs -f tradingbot + +# Last 100 lines +docker logs --tail 100 tradingbot + +# Since timestamp +docker logs --since 2024-12-12T10:00:00 tradingbot +``` + +### Resource Usage +```sh +# Stats +docker stats tradingbot + +# Processes +docker top tradingbot +``` + +--- + +## ?? CHECKLIST COMPLETO + +### Pre-Development +- [ ] Git repository synced (`git pull`) +- [ ] Branch corretto (`git branch`) +- [ ] Dependencies updated (`dotnet restore`) + +### Development +- [ ] Codice scritto e testato +- [ ] Build successful (`dotnet build`) +- [ ] Test locale OK (`dotnet run`) +- [ ] Docker test OK (`docker-compose up`) + +### Pre-Commit +- [ ] Codice formattato +- [ ] No secrets committati +- [ ] .gitignore aggiornato +- [ ] README aggiornato se necessario + +### Commit & Push +- [ ] `git status` verificato +- [ ] Commit message descrittivo +- [ ] Push successful +- [ ] Verifica su Gitea web UI + +### Deployment +- [ ] Pull su Unraid OK +- [ ] Docker build successful +- [ ] Container running +- [ ] Health check passing +- [ ] WebUI accessibile + +### Post-Deployment +- [ ] Logs verificati +- [ ] Nessun errore critico +- [ ] Funzionalitą testate +- [ ] Performance OK + +--- + +## ?? MAINTENANCE + +### Giornaliero +- Check logs per errori +- Verifica health endpoint +- Monitor resource usage + +### Settimanale +- Git pull updates +- Review commits +- Check disk space + +### Mensile +- Full backup +- Review performance metrics +- Update dependencies +- Security audit + +--- + +## ?? COMANDI RAPIDI + +```sh +# Development +git status +git add . +git commit -m "message" +git push origin main + +# Local Test +dotnet run +docker-compose up -d + +# Unraid Deploy +ssh root@unraid "/root/scripts/deploy-tradingbot.sh" + +# Check Status +docker ps | grep tradingbot +docker logs tradingbot --tail 50 + +# Restart +docker restart tradingbot + +# Update +git pull && docker-compose up -d --build +``` + +--- + +**?? Workflow pronto! Sviluppo ? Gitea ? Unraid automatizzato!** diff --git a/TradingBot/Program.cs b/TradingBot/Program.cs index 2da0e9a..1710f8f 100644 --- a/TradingBot/Program.cs +++ b/TradingBot/Program.cs @@ -13,8 +13,8 @@ builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); -// Alternative: Use real market data from CoinGecko (uncomment below and comment above) -// builder.Services.AddHttpClient(); +// Add health checks for Docker +builder.Services.AddHealthChecks(); var app = builder.Build(); @@ -25,12 +25,15 @@ if (!app.Environment.IsDevelopment()) // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } -app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true); + app.UseHttpsRedirection(); +app.UseStaticFiles(); app.UseAntiforgery(); -app.MapStaticAssets(); +// Health check endpoint for Docker +app.MapHealthChecks("/health"); + app.MapRazorComponents() .AddInteractiveServerRenderMode(); diff --git a/TradingBot/README.md b/TradingBot/README.md index 129d7f2..1e527a0 100644 --- a/TradingBot/README.md +++ b/TradingBot/README.md @@ -92,7 +92,7 @@ Un'applicazione Blazor Server avanzata per simulare e testare strategie di tradi - .NET 10 SDK - Visual Studio 2022+ o VS Code -### Installazione +### Installazione Locale ```bash # Clone repository git clone https://192.168.30.23/Alby96/Encelado @@ -105,6 +105,25 @@ dotnet restore dotnet run ``` +### ?? Deployment Docker + +#### Development +```sh +# Build +docker-compose build + +# Run +docker-compose up -d + +# Access +http://localhost:8080 +``` + +#### Production (Unraid) +Vedi documentazione completa: +- ?? [UNRAID_DEPLOYMENT.md](UNRAID_DEPLOYMENT.md) - Guida completa Unraid + Gitea +- ?? [DOCKER_QUICKSTART.md](DOCKER_QUICKSTART.md) - Quick start rapido + ### Uso 1. L'applicazione si avvia automaticamente in modalitą simulazione 2. Tutti i 15 asset sono attivi di default diff --git a/TradingBot/UNRAID_DEPLOYMENT.md b/TradingBot/UNRAID_DEPLOYMENT.md new file mode 100644 index 0000000..cbf621f --- /dev/null +++ b/TradingBot/UNRAID_DEPLOYMENT.md @@ -0,0 +1,517 @@ +# ?? DEPLOYMENT GUIDE - Unraid + Gitea + Docker + +Guida completa per deployare TradingBot su **Unraid** usando **Gitea** come sistema di controllo versione. + +--- + +## ?? PREREQUISITI + +### Su Unraid +- ? Docker installato (Community Applications) +- ? Gitea installato e configurato +- ? Accesso SSH abilitato +- ? Portainer installato (opzionale ma consigliato) + +### Sul PC di Sviluppo +- ? Git installato +- ? Accesso al server Unraid +- ? Repository Gitea configurato + +--- + +## ?? STEP 1: Configurazione Gitea + +### 1.1 Crea Repository su Gitea + +```sh +# Accedi a Gitea (esempio) +http://192.168.30.23:3000 + +# Crea nuovo repository +Nome: TradingBot +Descrizione: Automated Crypto Trading Bot +Privato: ? (consigliato) +``` + +### 1.2 Configura Git Remote (gią fatto) + +```sh +cd /path/to/TradingBot + +# Verifica remote (dovresti gią averlo) +git remote -v +# Output: +# origin https://192.168.30.23/Alby96/Encelado (fetch) +# origin https://192.168.30.23/Alby96/Encelado (push) + +# Se non configurato: +git remote add origin https://192.168.30.23/Alby96/Encelado +``` + +### 1.3 Push del Codice + +```sh +# Commit delle modifiche Docker +git add Dockerfile docker-compose.yml .dockerignore +git add build-docker.sh build-docker.bat +git add UNRAID_DEPLOYMENT.md + +git commit -m "Add Docker support and Unraid deployment" + +# Push su Gitea +git push origin main +``` + +--- + +## ?? STEP 2: Deployment su Unraid + +### Metodo A: Via Portainer (CONSIGLIATO) + +#### 2.1 Accedi a Portainer +``` +http://[UNRAID-IP]:9000 +``` + +#### 2.2 Crea Stack +1. **Stacks** ? **Add stack** +2. **Name**: `tradingbot` +3. **Build method**: `Git Repository` +4. **Repository URL**: `https://192.168.30.23/Alby96/Encelado` +5. **Repository reference**: `refs/heads/main` +6. **Compose path**: `TradingBot/docker-compose.yml` +7. **Authentication**: + - Username: `Alby96` + - Personal access token: (crea su Gitea) + +#### 2.3 Environment Variables (opzionali) +``` +TZ=Europe/Rome +ASPNETCORE_ENVIRONMENT=Production +``` + +#### 2.4 Deploy +Click **Deploy the stack** + +--- + +### Metodo B: Via SSH + Docker Compose + +#### 2.1 Connettiti a Unraid via SSH + +```sh +ssh root@[UNRAID-IP] +``` + +#### 2.2 Crea Directory Progetto + +```sh +# Vai nella directory appropriata +cd /mnt/user/appdata/ + +# Crea directory per TradingBot +mkdir -p tradingbot +cd tradingbot +``` + +#### 2.3 Clone Repository da Gitea + +```sh +# Clone del repository +git clone https://192.168.30.23/Alby96/Encelado.git . + +# Entra nella directory del progetto +cd TradingBot +``` + +#### 2.4 Build e Run + +```sh +# Build immagine Docker +docker-compose build + +# Avvia container +docker-compose up -d + +# Verifica logs +docker-compose logs -f +``` + +--- + +### Metodo C: Via Unraid Docker Template + +#### 2.1 Crea Template Personalizzato + +Crea file: `/boot/config/plugins/dockerMan/templates-user/my-TradingBot.xml` + +```xml + + + TradingBot + tradingbot:latest + https://192.168.30.23:5000/ + bridge + + sh + false + https://192.168.30.23/Alby96/Encelado + https://192.168.30.23/Alby96/Encelado + Automated Crypto Trading Bot con strategie personalizzabili + Tools: + http://[IP]:[PORT:8080] + + https://raw.githubusercontent.com/docker-library/docs/master/dotnet/logo.png + + + + 1234567890 + + + + 8080 + /mnt/user/appdata/tradingbot/data + Europe/Rome + +``` + +#### 2.2 Usa Template da Unraid UI +1. Docker ? Add Container +2. Select: `TradingBot` +3. Configure ports and volumes +4. Apply + +--- + +## ?? STEP 3: Aggiornamenti Automatici + +### 3.1 Setup Webhook su Gitea (opzionale) + +#### Su Gitea: +``` +Settings ? Webhooks ? Add Webhook +Payload URL: http://[UNRAID-IP]:9000/api/webhooks/[webhook-id] +Content type: application/json +Events: Push events +``` + +#### Su Portainer: +``` +Stacks ? tradingbot ? Webhooks ? Create webhook +Copia URL generato +``` + +### 3.2 Script di Aggiornamento Manuale + +```sh +#!/bin/bash +# update-tradingbot.sh + +cd /mnt/user/appdata/tradingbot/TradingBot + +# Pull latest changes +git pull origin main + +# Rebuild +docker-compose down +docker-compose build +docker-compose up -d + +echo "? TradingBot aggiornato!" +``` + +Salva come: `/root/scripts/update-tradingbot.sh` + +```sh +chmod +x /root/scripts/update-tradingbot.sh +``` + +--- + +## ?? STEP 4: Monitoraggio e Gestione + +### 4.1 Verifica Status Container + +```sh +# Via SSH +docker ps | grep tradingbot + +# Logs +docker logs tradingbot -f + +# Stats +docker stats tradingbot +``` + +### 4.2 Accesso WebUI + +``` +http://[UNRAID-IP]:8080 +``` + +### 4.3 Health Check + +```sh +curl http://[UNRAID-IP]:8080/health +``` + +--- + +## ?? STEP 5: Configurazione Avanzata + +### 5.1 Reverse Proxy (opzionale) + +Se usi **Nginx Proxy Manager** o **Traefik**: + +#### docker-compose.yml aggiornato: +```yaml +services: + tradingbot: + # ... altre configurazioni + labels: + - "traefik.enable=true" + - "traefik.http.routers.tradingbot.rule=Host(`trading.tuodominio.com`)" + - "traefik.http.services.tradingbot.loadbalancer.server.port=8080" + networks: + - traefik_proxy + - tradingbot-network + +networks: + traefik_proxy: + external: true +``` + +### 5.2 Backup Automatico + +Script backup: `/root/scripts/backup-tradingbot.sh` + +```sh +#!/bin/bash +BACKUP_DIR="/mnt/user/backups/tradingbot" +DATE=$(date +%Y%m%d_%H%M%S) + +mkdir -p $BACKUP_DIR + +# Backup volume dati +docker run --rm \ + -v tradingbot_tradingbot-data:/data \ + -v $BACKUP_DIR:/backup \ + alpine tar czf /backup/tradingbot-data-$DATE.tar.gz -C /data . + +echo "? Backup completato: tradingbot-data-$DATE.tar.gz" + +# Mantieni solo ultimi 7 backup +find $BACKUP_DIR -name "tradingbot-data-*.tar.gz" -mtime +7 -delete +``` + +Aggiungi a crontab: +```sh +crontab -e +# Backup giornaliero alle 3 AM +0 3 * * * /root/scripts/backup-tradingbot.sh +``` + +--- + +## ?? TROUBLESHOOTING + +### Container non si avvia + +```sh +# Check logs +docker logs tradingbot + +# Check network +docker network ls +docker network inspect tradingbot_tradingbot-network + +# Rebuild da zero +docker-compose down -v +docker-compose build --no-cache +docker-compose up -d +``` + +### Problemi di permessi + +```sh +# Fix ownership +docker exec tradingbot chown -R tradingbot:tradingbot /app/data +``` + +### Porta gią in uso + +```sh +# Trova processo che usa porta 8080 +netstat -tulpn | grep 8080 + +# Cambia porta in docker-compose.yml +ports: + - "8081:8080" # Usa 8081 invece +``` + +### Out of Memory + +Aumenta limits in docker-compose.yml: +```yaml +deploy: + resources: + limits: + memory: 2G # Da 1G a 2G +``` + +--- + +## ?? STEP 6: Registry Privato (opzionale) + +### 6.1 Setup Docker Registry su Unraid + +```sh +docker run -d \ + -p 5000:5000 \ + --restart=always \ + --name registry \ + -v /mnt/user/appdata/registry:/var/lib/registry \ + registry:2 +``` + +### 6.2 Build e Push + +```sh +# Tag image +docker tag tradingbot:latest 192.168.30.23:5000/tradingbot:latest + +# Push to registry +docker push 192.168.30.23:5000/tradingbot:latest +``` + +### 6.3 Deploy da Registry + +```yaml +# docker-compose.yml +services: + tradingbot: + image: 192.168.30.23:5000/tradingbot:latest + # ... resto configurazione +``` + +--- + +## ?? SECURITY BEST PRACTICES + +### 1. Non esporre porte pubblicamente +```sh +# Usa solo rete interna Unraid +# Accesso via VPN o Wireguard +``` + +### 2. SSL/TLS +```sh +# Usa reverse proxy con certificati SSL +# Let's Encrypt via Nginx Proxy Manager +``` + +### 3. Credenziali +```sh +# Non committare secrets in Git +# Usa Docker secrets o environment variables +``` + +### 4. Firewall +```sh +# Limita accesso solo a IP fidati +# Configura in Unraid Settings ? Network +``` + +--- + +## ?? MONITORING + +### Grafana + Prometheus (opzionale) + +```yaml +# monitoring-stack.yml +version: '3.8' +services: + prometheus: + image: prom/prometheus + volumes: + - ./prometheus.yml:/etc/prometheus/prometheus.yml + ports: + - "9090:9090" + + grafana: + image: grafana/grafana + ports: + - "3001:3000" + volumes: + - grafana-data:/var/lib/grafana + +volumes: + grafana-data: +``` + +--- + +## ?? CHECKLIST DEPLOYMENT + +### Pre-Deployment +- [ ] Codice committed su Gitea +- [ ] Dockerfile testato localmente +- [ ] docker-compose.yml configurato +- [ ] .dockerignore presente +- [ ] Environment variables definite + +### Deployment +- [ ] Repository clonato su Unraid +- [ ] Docker image built +- [ ] Container avviato correttamente +- [ ] WebUI accessibile +- [ ] Health check passing + +### Post-Deployment +- [ ] Logs verificati (no errori) +- [ ] Dati persistono dopo restart +- [ ] Backup configurato +- [ ] Monitoring attivo +- [ ] Documentazione aggiornata + +--- + +## ?? COMANDI UTILI + +```sh +# Build +./build-docker.sh [tag] + +# Start +docker-compose up -d + +# Stop +docker-compose down + +# Logs +docker-compose logs -f + +# Restart +docker-compose restart + +# Update +git pull && docker-compose up -d --build + +# Clean +docker-compose down -v +docker system prune -a +``` + +--- + +## ?? RISORSE + +- **Unraid Docs**: https://docs.unraid.net/ +- **Docker Docs**: https://docs.docker.com/ +- **Gitea Docs**: https://docs.gitea.io/ +- **Portainer Docs**: https://docs.portainer.io/ + +--- + +**?? Deployment completato! Il tuo TradingBot č ora in produzione su Unraid!** diff --git a/TradingBot/build-docker.bat b/TradingBot/build-docker.bat new file mode 100644 index 0000000..8eb3b09 --- /dev/null +++ b/TradingBot/build-docker.bat @@ -0,0 +1,29 @@ +@echo off +REM Script di build Docker per Windows + +echo Building TradingBot Docker Image... + +SET IMAGE_NAME=tradingbot +SET TAG=%1 +IF "%TAG%"=="" SET TAG=latest + +echo Building image: %IMAGE_NAME%:%TAG% + +docker build -t %IMAGE_NAME%:%TAG% -f Dockerfile . + +IF %ERRORLEVEL% NEQ 0 ( + echo Build failed! + exit /b %ERRORLEVEL% +) + +echo Build completed successfully! + +REM Tag come latest se diverso +IF NOT "%TAG%"=="latest" ( + echo Tagging as latest... + docker tag %IMAGE_NAME%:%TAG% %IMAGE_NAME%:latest +) + +echo Done! Run with: docker-compose up -d + +pause diff --git a/TradingBot/build-docker.sh b/TradingBot/build-docker.sh new file mode 100644 index 0000000..cdfce17 --- /dev/null +++ b/TradingBot/build-docker.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# Script di build Docker per TradingBot + +set -e + +echo "?? Building TradingBot Docker Image..." + +# Colori per output +GREEN='\033[0;32m' +BLUE='\033[0;34m' +RED='\033[0;31m' +NC='\033[0m' # No Color + +# Variabili +IMAGE_NAME="tradingbot" +TAG="${1:-latest}" +REGISTRY="${DOCKER_REGISTRY:-}" # Opzionale: tuo registry privato + +echo -e "${BLUE}?? Building image: ${IMAGE_NAME}:${TAG}${NC}" + +# Build dell'immagine +docker build \ + --build-arg BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ') \ + --build-arg VCS_REF=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown") \ + -t ${IMAGE_NAME}:${TAG} \ + -f Dockerfile \ + . + +echo -e "${GREEN}? Build completato con successo!${NC}" + +# Tag con latest +if [ "$TAG" != "latest" ]; then + echo -e "${BLUE}??? Tagging as latest...${NC}" + docker tag ${IMAGE_NAME}:${TAG} ${IMAGE_NAME}:latest +fi + +# Mostra info immagine +echo -e "${BLUE}?? Image info:${NC}" +docker images | grep ${IMAGE_NAME} | head -n 2 + +# Se registry č configurato, push +if [ ! -z "$REGISTRY" ]; then + echo -e "${BLUE}?? Pushing to registry: ${REGISTRY}${NC}" + docker tag ${IMAGE_NAME}:${TAG} ${REGISTRY}/${IMAGE_NAME}:${TAG} + docker push ${REGISTRY}/${IMAGE_NAME}:${TAG} + echo -e "${GREEN}? Pushed to registry!${NC}" +fi + +echo -e "${GREEN}?? Done! Run with: docker-compose up -d${NC}" diff --git a/TradingBot/docker-compose.yml b/TradingBot/docker-compose.yml new file mode 100644 index 0000000..8c86004 --- /dev/null +++ b/TradingBot/docker-compose.yml @@ -0,0 +1,52 @@ +version: '3.8' + +services: + tradingbot: + container_name: tradingbot + image: tradingbot:latest + build: + context: . + dockerfile: Dockerfile + ports: + - "8080:8080" + volumes: + # Persistenza dati applicazione + - tradingbot-data:/app/data + # Opzionale: mount locale per sviluppo + # - ./logs:/app/logs + environment: + # Configurazioni applicazione + - ASPNETCORE_ENVIRONMENT=Production + - ASPNETCORE_URLS=http://+:8080 + # Fuso orario (importante per trading!) + - TZ=Europe/Rome + # Opzionali - Configurazioni avanzate + # - TRADINGBOT__SimulationMode=true + # - TRADINGBOT__AutoStartBot=true + # - TRADINGBOT__UpdateIntervalSeconds=3 + restart: unless-stopped + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:8080/health"] + interval: 30s + timeout: 3s + retries: 3 + start_period: 10s + networks: + - tradingbot-network + # Resource limits (opzionali ma consigliati per Unraid) + deploy: + resources: + limits: + cpus: '2.0' + memory: 1G + reservations: + cpus: '0.5' + memory: 256M + +volumes: + tradingbot-data: + driver: local + +networks: + tradingbot-network: + driver: bridge