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

# 使用 Gunicorn 部署 Django 应用

> 在 Square Cloud 上部署 Django 应用：从环境变量读取设置，用 WhiteNoise 提供静态文件，并通过 START 命令在 80 端口运行 Gunicorn。

## 简介

要在 Square Cloud 上开发和托管 Django 应用，遵循一套结构化的配置和前置条件流程至关重要。本技术指南将涵盖整个过程，从初始设置到生产环境部署。

### 前置条件

* **Square Cloud 账户**：通过[注册页面](https://squarecloud.app/zh/signup)使用你的邮箱进行注册。
* **有效套餐**：为你的应用提供专属资源和优化的性能。查看我们[可用的套餐](https://squarecloud.app/zh/pricing)，选择最适合你需求的方案。

> [!NOTE]

本指南运行在 [Python 运行时](https://docs.squarecloud.app/zh/articles/getting-started-with-python.md)上。已于 2026 年 9 月在 Python 3.13 上使用 Django 6 测试。

## 创建项目

你的电脑上需要安装 Python 和 pip。如果尚未安装，可以从 [Python 官方网站](https://www.python.org/downloads/) 下载 Python。

### 安装库

安装 Django、生产服务器 Gunicorn，以及用于提供静态文件的 WhiteNoise：

```bash theme={"system"}
pip install django gunicorn whitenoise
```

### 开发项目

创建一个新的 Django 项目并进入其文件夹：

```bash theme={"system"}
django-admin startproject mysite
cd mysite
```

这会创建 `manage.py` 以及包含 `settings.py`、`urls.py` 和 `wsgi.py` 的 `mysite/` 包。要添加一个基础路由，请编辑 `mysite/urls.py`：

```python mysite/urls.py theme={"system"}
from django.contrib import admin
from django.http import HttpResponse
from django.urls import path

def index(request):
    return HttpResponse("Hello, World!")

urlpatterns = [
    path("", index),
    path("admin/", admin.site.urls),
]
```

### 为生产环境配置设置

永远不要在代码中硬编码密钥。在 `mysite/settings.py` 中，从环境变量读取密钥和生产环境标志，信任你网站的 HTTPS 源，并启用 WhiteNoise。生成的其余设置保持不变：

```python mysite/settings.py theme={"system"}
import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
DEBUG = os.environ.get("DJANGO_DEBUG", "False") == "True"
ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS", "localhost,127.0.0.1").split(",")

# HTTPS address of your site, required for forms (CSRF) behind the Square Cloud proxy
CSRF_TRUSTED_ORIGINS = ["https://mysite.squareweb.app"]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",  # right after SecurityMiddleware
    # ... keep the other middleware generated by Django
]

STATIC_URL = "static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
STORAGES = {
    "default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
    "staticfiles": {"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage"},
}
```

将 `mysite.squareweb.app` 替换为你的子域名或自定义域名。然后通过控制面板或使用 [`squarecloud app env set`](https://docs.squarecloud.app/zh/cli-reference/environment-variables#squarecloud-app-env-set)，在应用中设置以下[环境变量](https://docs.squarecloud.app/zh/platform/environment-variables.md)：

| 变量 | 值 |
| - | - |
| `DJANGO_SECRET_KEY` | 一个较长的随机值，例如 `python -c "import secrets; print(secrets.token_urlsafe(50))"` 的输出 |
| `DJANGO_DEBUG` | `False`（生产环境中绝不要设为 `True`） |
| `DJANGO_ALLOWED_HOSTS` | 你的域名，例如 `mysite.squareweb.app`。多个域名用逗号分隔 |

> [!NOTE]
>
> 要在本地运行项目，请在终端中设置 `DJANGO_SECRET_KEY`（任意值）和 `DJANGO_DEBUG=True`，然后运行 `python manage.py runserver`。

然后在 `manage.py` 旁边的 `requirements.txt` 文件中列出依赖。Square Cloud 会在启动应用之前用 pip 安装它们。其中至少需要列出：

```txt requirements.txt theme={"system"}
django
gunicorn
whitenoise
```

> [card] [requirements.txt](https://docs.squarecloud.app/zh/articles/how-to-create-your-requirements.md)
>
> Python 项目中用于列出项目所需的所有外部库和依赖项的标准文件。文件中的每一行指定一个通过 pip（Python 的包管理器）安装的包。

> [card] [pyproject.toml](https://docs.squarecloud.app/zh/articles/how-to-create-your-pyproject.md)
>
> Python 项目的现代配置文件，用于声明项目元数据和依赖项。没有 requirements.txt 时，Square Cloud 会使用 pip install . 安装这些依赖项。

## 选择生产服务器

Django 内置的开发服务器（`runserver`）不适合用于生产环境。请使用面向生产的 WSGI 服务器 Gunicorn，并由下面的 `START` 命令启动它。有关 worker 设置和其他选项，请参阅 Gunicorn 指南：

> [card] [Gunicorn](https://docs.squarecloud.app/zh/tutorials/python/how-to-use-gunicorn.md)
>
> Gunicorn 是一个用于 UNIX 的 Python WSGI HTTP 服务器。它采用预派生（pre-fork）工作进程模型，会派生多个工作进程来处理请求。
> 这使它成为在生产环境中运行 Python Web 应用的绝佳选择。

## 端口和主机

> [!NOTE]

下面的 `START` 命令会将 Gunicorn 绑定到 `0.0.0.0:80`：即所有网络接口，以及 Square Cloud 路由到你应用的端口。Django 本身没有需要修改的端口设置。

## 配置 Square Cloud

在 `manage.py` 旁边创建 `squarecloud.app` 文件：

```systemd squarecloud.app theme={"system"}
MAIN=manage.py
MEMORY=512
VERSION=recommended
DISPLAY_NAME=My Django app
SUBDOMAIN=mysite
START=python manage.py collectstatic --noinput && python manage.py migrate --noinput && python -m gunicorn mysite.wsgi --bind 0.0.0.0:80
```

每次启动时，该命令会：

* `collectstatic` 将你的静态文件复制到 `STATIC_ROOT`，由 WhiteNoise 从那里提供这些文件。
* `migrate` 应用待执行的数据库迁移。数据库已是最新时，它不会做任何事。
* `python -m gunicorn mysite.wsgi --bind 0.0.0.0:80` 在 80 端口和所有网络接口上提供 `mysite` 项目的 WSGI 应用。

`MAIN=manage.py` 会选择 Python 运行时。通过控制面板上传时，请设置相同的主文件和启动命令。

## ZIP 中包含哪些文件

* `manage.py` 以及包含你的应用和模板的 `mysite/` 包。
* `requirements.txt`。
* `squarecloud.app`。

`manage.py`、`requirements.txt` 和 `squarecloud.app` 必须位于 ZIP 的根目录。不要包含 `.venv`、`__pycache__`、`staticfiles/`（每次启动时由 `collectstatic` 重新生成）以及本地的 `db.sqlite3`。

## 部署并验证

### 通过控制面板

**1. 访问上传页面**

访问[上传页面](https://squarecloud.app/zh/dashboard/new)并上传你的项目 zip 文件。

**2. 配置你的环境**

上传 zip 后，你需要为项目配置名称、主文件或运行时环境以及其他设置。\
如果你上传的是 Web 项目，请务必选择 "Web Publication" 并为项目设置子域名。

**3. 部署你的项目**

最后，点击 "Deploy" 按钮，即可将项目托管到 Square Cloud。\
部署完成后，你可以在控制面板中监控项目的状态和日志。

![正在上传应用到 Square Cloud](https://cdn.squarecloud.app/docs/articles/dashboard/uploading.gif)

**4. 确认你的应用已上线**

首次部署通常在一分钟内完成。在[控制面板](https://squarecloud.app/zh/dashboard)中，等待你的应用状态显示为运行中，并检查日志中是否有启动错误。\
如果你部署的是网站或 API，请在浏览器中打开 `https://<your-subdomain>.squareweb.app`，你应该能看到应用正常响应。如果你部署的是机器人，发送一条命令确认它已上线。
\[!TIP] 应用无法启动？请参见[故障排除指南](https://docs.squarecloud.app/zh/platform/troubleshooting/app-wont-start.md)，了解最常见的原因和解决方法。

### 通过 CLI

要使用此方法，你的项目根目录中需要有一个名为 `squarecloud.app` 的配置文件。它告诉 Square Cloud 如何运行你的应用。

> [card] [配置文件指南](https://docs.squarecloud.app/zh/getting-started/config-file.md)
>
> 了解如何创建定义你应用环境的 `squarecloud.app` 配置文件。

**1. 安装 CLI**

安装 [Square Cloud CLI](https://docs.squarecloud.app/zh/cli-reference/installation.md)。如果你已经安装，运行同一条命令即可更新：

```bash macOS, Linux, and WSL theme={"system"}
curl -fsSL https://cli.squarecloud.app/install | bash
```

```bash Windows with npm theme={"system"}
npm install -g @squarecloud/cli@latest
```

**2. 登录**

运行下面的命令。它会打开你的浏览器：在浏览器中批准登录后，CLI 即可使用。无需复制任何 API 密钥。如需在脚本和 CI 中使用，请参阅 [CLI 身份验证](https://docs.squarecloud.app/zh/cli-reference/authentication.md)。

```bash theme={"system"}
squarecloud auth login
```

**3. 上传你的项目**

在项目文件夹中运行下面的命令。CLI 会将当前文件夹打包为 zip（排除 [`squarecloud.ignore`](https://docs.squarecloud.app/zh/getting-started/squarecloud-ignore) 中列出的内容）并上传：

```bash theme={"system"}
squarecloud upload
```

要上传你自己创建的 zip，请通过 `--file` 传入：

```bash theme={"system"}
squarecloud upload --file <path/to/zip>
```

**4. 确认你的应用已上线**

首次部署通常在一分钟内完成。直接在终端中检查你的应用状态和日志：

```bash theme={"system"}
squarecloud app status
squarecloud app logs
```

如果你部署的是网站或 API，请在浏览器中打开 `https://<your-subdomain>.squareweb.app`，你应该能看到应用正常响应。如果你部署的是机器人，发送一条命令确认它已上线。
\[!TIP] 应用无法启动？请参见[故障排除指南](https://docs.squarecloud.app/zh/platform/troubleshooting/app-wont-start.md)，了解最常见的原因和解决方法。

## 常见错误

### 自定义域名

> [card]
>
> 若要使用自定义域名（例如 `mysite.com`）来代替默认 URL `mysite.squareweb.app`，你需要 **Standard 计划或更高等级**。默认 URL 由配置文件中的 **SUBDOMAIN** 字段决定。要连接你的域名，请参阅[如何设置自己的域名](https://help.squarecloud.app/en-us/article/how-to-set-up-your-own-domain-cnamedns-1fzbrgh/)。

### 最低内存要求

> [card]
>
> 网站和 API 的**最低要求为 512MB RAM**，足以在静态运行时上托管静态构建产物。对于在服务器上渲染页面的应用（Next.js、Nuxt、Angular SSR 等），我们建议**至少 1GB RAM**。对于更大型的应用，请分配更多 RAM，以防止应用内存耗尽而崩溃。

### 找不到此站点。

> [card]
>
> 请检查**子域名/域名**是否与 **SUBDOMAIN** 字段或**自定义域名设置**中配置的内容一致。如果你刚上传站点，请等待最多 **60 秒**，让 Square 启用**首次访问**。

### 站点响应超时……

> [card]
>
> 你的服务器必须监听**端口 80** 和**主机 0.0.0.0**。Square Cloud 会在你的应用中设置 **PORT**（`80`）和 **HOST**（`0.0.0.0`）环境变量：请在代码中读取它们，而不要硬编码其他值。只监听 `localhost` 或 `127.0.0.1` 的服务器永远收不到请求。

### KeyError: 'DJANGO\_SECRET\_KEY'

缺少该环境变量。请按照[为生产环境配置设置](#为生产环境配置设置)中的说明设置 `DJANGO_SECRET_KEY`，然后重启应用。

### Bad Request (400)

你打开的地址不在 `DJANGO_ALLOWED_HOSTS` 中。请将你的子域名或自定义域名添加进去，然后重启应用。

## 后续步骤

> [card] [环境变量](https://docs.squarecloud.app/zh/platform/environment-variables.md)
>
> 将密钥和设置放在代码之外，并在运行时读取。

> [card] [自定义域名](https://help.squarecloud.app/en-us/article/how-to-set-up-your-own-domain-cnamedns-1fzbrgh/)
>
> 在 Standard 及以上计划中，用你自己的域名提供应用。

> [card] [故障排除](https://docs.squarecloud.app/zh/platform/troubleshooting.md)
>
> 修复无法启动的应用或没有响应的站点。

有关 Django 的更多信息，请参阅 [Django 官方文档](https://docs.djangoproject.com/en/stable/)及其[部署检查清单](https://docs.djangoproject.com/en/stable/howto/deployment/checklist/)。

## 联系我们

如果你仍然遇到**技术问题**，我们的**专业支持团队**可以为你提供帮助。[**联系我们**](https://squarecloud.app/zh/support)，我们很乐意协助你解决任何问题，支持质量正是开发者给予 Square Cloud [**4.9/5 评分（共 402 条评价）**](https://www.trustpilot.com/review/squarecloud.app)（Google 与 Trustpilot）的重要原因之一。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.