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

# 使用 Docker 将 Django 应用与 Postgres 和 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="将使用 Postgres 和 Redis 的 Django 应用 Docker 化" description="Devin 编写一个多阶段 Dockerfile 和一个包含 Django、PostgreSQL 与 Redis 的 docker-compose.yml，然后构建并运行整套服务以验证其可用性。" prompt="将 src/ 中的 Django API Docker 化。它使用 PostgreSQL 作为数据库，使用 Redis 进行缓存和 Celery 任务队列。使用基于 python:3.12-slim 的多阶段 Dockerfile，docker-compose.yml 中包含 Django（gunicorn）、PostgreSQL 16、Redis 7，以及一个 Celery worker。以非 root 用户运行，并在 /api/health/ 上添加健康检查。构建后运行 docker-compose up，验证 API 有响应，并在容器内运行测试套件。如果有任何失败，进行调试和修复——持续迭代直到一切正常工作。在整套服务能够干净启动且所有测试通过之前，不要创建 PR（拉取请求）。" category="Feature Development" features="" />

<div className="uc-detail-wrapper">
  <Tip>不想手动配置？将本页链接粘贴到 Devin 会话中，让它为你完成所有设置。</Tip>

  <Steps>
    <Step title="（可选）使用 Ask Devin 规划项目范围">
      如果你不确定你的 Django 应用依赖哪些服务，或者项目结构如何，可以先使用 [Ask Devin](https://app.devin.ai/search?utm_source=docs\&utm_medium=use-case-gallery) 来了解情况：

      <PromptBlock agent="ada">
        ```txt 为容器化梳理 Django 项目的范围 theme={null}
        我们在 src/ 中的 Django 应用依赖什么？
        1. 它连接了哪些数据库和缓存？
        2. 它是否使用 Celery 或其他后台任务 worker？
        3. requirements.txt 或 pyproject.toml 里有哪些依赖？
        4. 是否有任何现成的 Docker 文件或部署配置？
        5. 应用如何处理静态文件和媒体文件？
        ```
      </PromptBlock>

      你也可以直接从 Ask Devin 发起 Devin 会话，它会把之前获取的全部信息作为上下文继续使用。
    </Step>

    <Step title="将你的 Django 项目和依赖项交给 Devin">
      将 Devin 指向需要容器化的 Django 项目，并说明任何特定要求——例如基础镜像偏好、应用依赖的服务或镜像大小限制。Devin 会读取你的 `requirements.txt` 或 `pyproject.toml` 来推断其余内容。

      <PromptBlock>
        ```txt Dockerize Django API with Postgres and Redis theme={null}
        Dockerize the Django API in src/. It uses PostgreSQL for the database
        and Redis for caching and Celery task queues.

        - Multi-stage Dockerfile: install dependencies in a builder stage,
          copy only the venv into a slim python:3.12-slim runtime image
        - docker-compose.yml with Django (gunicorn), PostgreSQL 16, and Redis 7
        - .dockerignore that excludes tests, docs, .git, and __pycache__
        - Run as non-root user
        - Health check on /api/health/
        - Celery worker as a separate service in compose

        ## Testing & verification
        - Build the image and run docker-compose up
        - Wait for all services to be healthy
        - Verify the API responds on localhost:8000/api/health/
        - Run the Django test suite inside the container
        - If anything fails — build errors, missing env vars, connection
          issues, failing tests — debug and fix it. Keep iterating until
          the entire stack starts cleanly and all tests pass.
        - Do not open a PR until everything works end-to-end
        ```
      </PromptBlock>
    </Step>

    <Step title="Devin 调研并构建">
      Devin 读取你的 Django 项目及依赖文件以理解构建流程，并据此创建 Docker 配置：

      1. **读取依赖文件** — 解析 `requirements.txt` 或 `pyproject.toml`，识别 Django、psycopg2、redis、celery 和 gunicorn
      2. **编写 Dockerfile** — 创建一个多阶段构建，在构建阶段安装依赖，并将虚拟环境复制到精简的 `python:3.12-slim` 运行时镜像中

      ```dockerfile theme={null}
      # ---- 构建阶段 ----
      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

      # ---- 运行阶段 ----
      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. **编写 docker-compose.yml** — 添加 Django、PostgreSQL、Redis 和一个 Celery worker，并配置健康检查、数据卷和共享网络

      ```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. **添加 .dockerignore** — 排除不属于构建上下文的文件 (`__pycache__`、`.git`、`tests/`、`docs/`、`*.pyc`)
      5. **运行 `docker compose up --build`** — 构建镜像并在 Devin 的终端中启动所有服务
      6. **验证应用** — 通过 curl 调用 `/api/health/` 来确认 Django 能正常无误地启动、连接到 PostgreSQL，并访问 Redis
    </Step>

    <Step title="通过斜杠命令引导会话">
      在会话期间使用斜杠命令来引导 Devin 的工作流程：

      * **`/plan`** — 让 Devin 在编写任何 Docker 配置之前先给出实现方案概要。审查该方案并提出修改建议。
      * **`/test`** — 告诉 Devin 重新构建并重新验证容器栈。每次更改后使用此命令以尽早发现问题。
      * **`/review`** — 让 Devin 在打开 PR 之前审查自己的 Dockerfile 和 Compose 配置，检查安全问题、镜像大小以及最佳实践。
    </Step>

    <Step title="验证和迭代">
      一旦 Devin 提交 PR (pull request 拉取请求) ，审查生成的文件。常见的后续跟进示例：

      <PromptBlock>
        ```txt 优化镜像大小 theme={null}
        当前 Docker 镜像为 520MB。将其缩小体积——确保我们没有复制
        不必要的文件，从 venv 中删除 .pyc 文件，并从最终镜像中移除 pip。
        ```
      </PromptBlock>

      <PromptBlock>
        ```txt 添加开发环境热重载 theme={null}
        为本地开发添加一个 docker-compose.override.yml，用于挂载
        源码目录，并运行带自动重载的 Django 开发服务器，
        而不是使用 gunicorn。
        ```
      </PromptBlock>

      <PromptBlock>
        ```txt 添加 CI Docker 构建 theme={null}
        创建一个 GitHub Actions 工作流，在每个 PR 上构建 Docker 镜像，
        在容器内运行 pytest，并在合并到 main 时推送到 ECR。
        使用 git SHA 作为镜像标签。
        ```
      </PromptBlock>
    </Step>

    <Step title="使用 Devin Review 审查该 PR">
      一旦 Devin 创建 PR，使用 [Devin Review](https://app.devin.ai/review?utm_source=docs\&utm_medium=use-case-gallery) 来审查 Docker 配置。Devin Review 可以发现安全问题 (以 root 用户身份运行、暴露的机密信息) 、缺失的最佳实践 (没有 `.dockerignore`、没有健康检查) ，以及与你现有基础设施不一致的地方。
    </Step>
  </Steps>
</div>
