> ## Documentation Index
> Fetch the complete documentation index at: https://docs.devinenterprise.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Dockerizzare un'applicazione Django con Postgres e Redis

export const UseCaseHero = ({title, description, prompt, category, features, devinUrl, agent, intent, playbookId, type}) => {
  const encodedPrompt = encodeURIComponent(prompt || '');
  const tag = 'docs-use-case-gallery';
  const utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=hero-cta';
  const agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  const devinHref = type === 'schedule' ? 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + (prompt ? '&prompt=' + encodedPrompt : '') : type === 'review' ? 'https://app.devin.ai/review?' + utm : agent === 'ada' ? 'https://app.devin.ai/search?' + utm + '&noSubmit=true' + (prompt ? '&prompt=' + encodedPrompt : '') : devinUrl ? devinUrl.includes('?') ? devinUrl + '&' + utm + agentParams : devinUrl + '?' + utm + agentParams : prompt ? 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encodedPrompt : 'https://app.devin.ai/?' + utm + agentParams;
  const buttonLabel = type === 'schedule' ? 'Schedule in Devin ↗' : type === 'review' ? 'Set Up Devin Review ↗' : agent === 'advanced' ? 'Try in Devin ↗' : agent === 'dana' ? 'Try in Dana ↗' : agent === 'ada' ? 'Try in Ask Devin ↗' : 'Try in Devin ↗';
  const featureList = features ? features.split(',').map(f => f.trim()) : [];
  return <div className="uc-hero">
      <div className="uc-hero-inner">
        <div className="uc-hero-left">
          <h1 className="uc-hero-title">{title}</h1>
          <p className="uc-hero-desc">{description}</p>
          <div>
            <a href={devinHref} target="_blank" rel="noopener noreferrer" className="try-in-devin-btn">
              {buttonLabel}
            </a>
          </div>
        </div>
        <div className="uc-hero-meta">
          <div className="uc-meta-item">
            <span className="uc-meta-label">Author</span>
            <span className="uc-meta-value">Cognition</span>
          </div>
          <div className="uc-meta-item">
            <span className="uc-meta-label">Category</span>
            <span className="uc-meta-value">{category}</span>
          </div>
          {featureList.length > 0 && <div className="uc-meta-item">
              <span className="uc-meta-label">Features</span>
              <span className="uc-meta-value">{featureList.join(', ')}</span>
            </div>}
        </div>
      </div>
    </div>;
};

export const PromptBlock = ({children, type, agent, intent, playbookId}) => {
  var utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=prompt-block';
  var tag = 'docs-use-case-gallery';
  var agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  var label = type === 'schedule' ? 'Schedule in Devin' : type === 'playbook' ? 'Create Playbook' : type === 'knowledge' ? 'Add to Knowledge' : agent === 'advanced' ? 'Try in Devin' : agent === 'dana' ? 'Try in Dana' : agent === 'ada' ? 'Try in Ask Devin' : 'Try in Devin';
  var buildUrl = function (text) {
    var encoded = encodeURIComponent(text);
    if (type === 'schedule') return 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + '&prompt=' + encoded;
    if (type === 'playbook') return 'https://app.devin.ai/settings/playbooks/create?' + utm + '&body=' + encoded;
    if (type === 'knowledge') return 'https://app.devin.ai/knowledge?' + utm + '&body=' + encoded;
    if (agent === 'ada') return 'https://app.devin.ai/search?' + utm + '&noSubmit=true&prompt=' + encoded;
    return 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encoded;
  };
  const ref = React.useRef(null);
  const [href, setHref] = React.useState('#');
  React.useEffect(() => {
    if (!ref.current) return;
    var codeEl = ref.current.querySelector('pre code');
    if (codeEl) {
      var text = codeEl.textContent.trim();
      if (text) setHref(buildUrl(text));
    }
    var header = ref.current.querySelector('[data-component-part="code-block-header"]');
    if (header && !header.querySelector('.prompt-block-devin-link')) {
      var link = document.createElement('a');
      link.href = href;
      link.target = '_blank';
      link.rel = 'noopener noreferrer';
      link.className = 'prompt-block-devin-link';
      link.style.cssText = 'display:inline-flex;align-items:center;gap:6px;text-decoration:none;color:#fff;font-size:11px;font-weight:500;padding:4px 10px;border-radius:6px;white-space:nowrap;background:#317CFF;transition:background 0.2s;margin-left:8px;';
      link.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg> ' + label;
      link.onmouseenter = function () {
        link.style.background = '#2968D9';
      };
      link.onmouseleave = function () {
        link.style.background = '#317CFF';
      };
      header.appendChild(link);
    }
    var existingLink = ref.current.querySelector('.prompt-block-devin-link');
    if (existingLink && href !== '#') existingLink.href = href;
  });
  return <div className="prompt-block" ref={ref}>{children}</div>;
};

<UseCaseHero title="Dockerizzare un'app Django con Postgres e Redis" description="Devin scrive un Dockerfile multi-stage, un file docker-compose.yml con Django, PostgreSQL e Redis, quindi effettua la build ed esegue lo stack per verificare che funzioni." prompt="Dockerizza la Django API in src/. Usa PostgreSQL per il database e Redis per la cache e le code di task Celery. Dockerfile multi-stage con python:3.12-slim, docker-compose.yml con Django (gunicorn), PostgreSQL 16, Redis 7 e un worker Celery. Esegui come utente non root, health check su /api/health/. Effettua la build, avvia docker-compose up, verifica che l'API risponda, esegui la test suite all'interno del container. Se qualcosa fallisce, effettua il debug e correggi i problemi — continua a iterare finché tutto non funziona. Non aprire una PR finché l'intero stack non si avvia correttamente e tutti i test non passano." category="Sviluppo di funzionalità" features="" />

<div className="uc-detail-wrapper">
  <Tip>Non vuoi configurarlo manualmente? Incolla un collegamento a questa pagina in una sessione di Devin e chiedigli di impostare tutto per te.</Tip>

  <Steps>
    <Step title="(Facoltativo) Definisci l'ambito del progetto con Ask Devin">
      Se non sei sicuro da quali servizi dipenda la tua app Django o di come è strutturato il progetto, usa [Ask Devin](https://app.devin.ai/search?utm_source=docs\&utm_medium=use-case-gallery) per analizzarlo prima:

      <PromptBlock agent="ada">
        ```txt Definisci l'ambito del progetto Django per la containerizzazione theme={null}
        Da cosa dipende la nostra app Django in src/?
        1. A quali database e cache si connette?
        2. Usa Celery o altri worker in background?
        3. Cosa c'è in requirements.txt o pyproject.toml?
        4. Ci sono Dockerfile o configurazioni di deployment esistenti?
        5. Come gestisce l'app i file statici e i contenuti multimediali?
        ```
      </PromptBlock>

      Puoi anche avviare una sessione di Devin direttamente da Ask Devin, e porterà con sé tutto il contesto che ha appreso.
    </Step>

    <Step title="Fornisci a Devin il tuo progetto Django e i relativi requirements">
      Indirizza Devin al progetto Django da containerizzare e indica eventuali requisiti specifici — ad esempio preferenze per l'immagine di base, servizi da cui l'app dipende o vincoli sulle dimensioni dell'immagine. Devin legge i tuoi file `requirements.txt` o `pyproject.toml` per occuparsi del resto.

      <PromptBlock>
        ```txt Dockerize Django API with Postgres and Redis theme={null}
        Dockerizza l'API Django in src/. Usa PostgreSQL come database
        e Redis per la cache e le queue di task Celery.

        - Dockerfile multi-stage: installa le dipendenze in uno stage builder,
          copia solo il venv in un'immagine runtime slim python:3.12-slim
        - docker-compose.yml con Django (gunicorn), PostgreSQL 16 e Redis 7
        - .dockerignore che esclude tests, docs, .git e __pycache__
        - Esecuzione come utente non-root
        - Health check su /api/health/
        - Worker Celery come servizio separato in compose

        ## Testing & verification
        - Builda l'immagine ed esegui docker-compose up
        - Attendi che tutti i servizi siano in stato healthy
        - Verifica che l'API risponda su localhost:8000/api/health/
        - Esegui la test suite Django all'interno del container
        - Se qualcosa fallisce — errori di build, variabili d'ambiente mancanti,
          problemi di connessione, test falliti — effettua il debug e risolvi.
          Continua a iterare finché l'intero stack non si avvia correttamente
          e tutti i test non passano.
        - Non aprire una PR finché non funziona tutto end-to-end
        ```
      </PromptBlock>
    </Step>

    <Step title="Devin analizza e realizza">
      Devin legge il tuo progetto Django e i file di dipendenze per comprendere il processo di build, quindi genera la configurazione Docker:

      1. **Legge i file di dipendenze** — Analizza `requirements.txt` o `pyproject.toml` e identifica Django, psycopg2, redis, celery e gunicorn
      2. **Scrive il Dockerfile** — Crea una build multi-stage che installa le dipendenze in una fase builder e copia l'ambiente virtuale in un’immagine di runtime minimale `python:3.12-slim`

      ```dockerfile theme={null}
      # ---- Builder ----
      FROM python:3.12-slim AS builder
      WORKDIR /app
      COPY requirements.txt .
      RUN python -m venv /opt/venv \
          && /opt/venv/bin/pip install --no-cache-dir -r requirements.txt

      # ---- Runtime ----
      FROM python:3.12-slim
      RUN groupadd -r django && useradd -r -g django django
      COPY --from=builder /opt/venv /opt/venv
      ENV PATH="/opt/venv/bin:$PATH"
      WORKDIR /app
      COPY src/ .
      RUN python manage.py collectstatic --noinput
      EXPOSE 8000
      USER django
      CMD ["gunicorn", "config.wsgi:application", "--bind", "0.0.0.0:8000", "--workers", "3"]
      ```

      3. **Genera il file docker-compose.yml** — Aggiunge Django, PostgreSQL, Redis e un worker Celery con health check, volumi e una rete condivisa

      ```yaml theme={null}
      services:
        web:
          build: .
          ports:
            - "8000:8000"
          env_file: .env
          depends_on:
            db:
              condition: service_healthy
            redis:
              condition: service_healthy
          healthcheck:
            test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/api/health/')"]
            interval: 10s
            retries: 3

        db:
          image: postgres:16-alpine
          environment:
            POSTGRES_DB: app_db
            POSTGRES_USER: app_user
            POSTGRES_PASSWORD: app_pass
          volumes:
            - pgdata:/var/lib/postgresql/data
          healthcheck:
            test: ["CMD-SHELL", "pg_isready -U app_user -d app_db"]
            interval: 5s
            retries: 5

        redis:
          image: redis:7-alpine
          healthcheck:
            test: ["CMD", "redis-cli", "ping"]
            interval: 5s
            retries: 5

        celery:
          build: .
          command: celery -A config worker -l info
          env_file: .env
          depends_on:
            db:
              condition: service_healthy
            redis:
              condition: service_healthy

      volumes:
        pgdata:
      ```

      4. **Aggiunge .dockerignore** — Esclude i file che non devono far parte del contesto di build (`__pycache__`, `.git`, `tests/`, `docs/`, `*.pyc`)
      5. **Esegue `docker compose up --build`** — Costruisce l'immagine e avvia tutti i servizi nel terminale di Devin
      6. **Verifica l'app** — Esegue un curl su `/api/health/` per confermare che Django si avvia correttamente, si connette a PostgreSQL e raggiunge Redis
    </Step>

    <Step title="Gestisci la sessione con i comandi slash">
      Utilizza i comandi slash durante la sessione per guidare il flusso di lavoro di Devin:

      * **`/plan`** — Chiedi a Devin di descrivere il proprio approccio prima di scrivere qualsiasi configurazione Docker. Rivedi il piano e suggerisci modifiche.
      * **`/test`** — Di' a Devin di ricostruire e verificare nuovamente lo stack di container. Usa questo comando dopo ogni modifica per intercettare i problemi in anticipo.
      * **`/review`** — Chiedi a Devin di rivedere il proprio Dockerfile e la configurazione Docker Compose per problemi di sicurezza, dimensione dell'immagine e best practice prima di aprire la pull request (PR).
    </Step>

    <Step title="Verificare e iterare">
      Una volta che Devin apre la PR, rivedi i file generati. Follow-up comuni:

      <PromptBlock>
        ```txt Ottimizza la dimensione dell'immagine theme={null}
        L'immagine Docker è di 520MB. Riducila — assicurati di non copiare
        file non necessari, rimuovi i file .pyc dal venv ed elimina pip
        dall'immagine finale.
        ```
      </PromptBlock>

      <PromptBlock>
        ```txt Aggiungi l'hot-reload per lo sviluppo theme={null}
        Aggiungi un docker-compose.override.yml per lo sviluppo locale che monti
        la directory sorgente ed esegua il server di sviluppo di Django con auto-reload
        invece di gunicorn.
        ```
      </PromptBlock>

      <PromptBlock>
        ```txt Aggiungi il build Docker in CI theme={null}
        Crea un workflow di GitHub Actions che effettui il build dell'immagine Docker a
        ogni PR, esegua pytest all'interno del container e faccia il push su ECR al
        merge su main. Tagga con lo SHA Git.
        ```
      </PromptBlock>
    </Step>

    <Step title="Rivedi la PR con Devin Review">
      Una volta che Devin apre la PR, utilizza [Devin Review](https://app.devin.ai/review?utm_source=docs\&utm_medium=use-case-gallery) per verificare la configurazione Docker. Devin Review può individuare problemi di sicurezza (esecuzione come root, segreti esposti), best practice mancanti (assenza di un file `.dockerignore`, mancanza di health check) e incoerenze con la tua infrastruttura esistente.
    </Step>
  </Steps>
</div>
