为 Azure 应用服务配置 Linux Python 应用Configure a Linux Python app for Azure App Service

本文介绍了 Azure 应用服务如何运行 Python 应用、你如何将现有应用迁移到 Azure 以及如何按需自定义应用服务的行为。This article describes how Azure App Service runs Python apps, how you can migrate existing apps to Azure, and how you can customize the behavior of App Service when needed. 必须连同所有必需的 pip 模块一起部署 Python 应用。Python apps must be deployed with all the required pip modules.

部署 Git 存储库zip 包时,应用服务部署引擎会自动激活虚拟环境并运行 pip install -r requirements.txtThe App Service deployment engine automatically activates a virtual environment and runs pip install -r requirements.txt for you when you deploy a Git repository, or a zip package.

对于在应用服务中使用内置 Linux 容器的 Python 开发人员,本指南为其提供了关键概念和说明。This guide provides key concepts and instructions for Python developers who use a built-in Linux container in App Service. 若从未使用过 Azure 应用服务,请先按照 Python 快速入门以及将 Python 与 PostgreSQL 配合使用教程进行操作。If you've never used Azure App Service, first follow the Python quickstart and Python with PostgreSQL tutorial.

可使用 Azure 门户 或 Azure CLI 进行配置:You can use either the Azure portal or the Azure CLI for configuration:

备注

Linux 是目前在应用服务中用于运行 Python 应用的推荐选项。Linux is currently the recommended option for running Python apps in App Service. 有关 Windows 选项的信息,请参阅 Windows 风格的应用服务上的 PythonFor information on the Windows option, see Python on the Windows flavor of App Service.

配置 Python 版本Configure Python version

  • Azure 门户:按照针对 Linux 容器的 配置常规设置中所述,使用“配置”页上的“常规设置”选项卡 。Azure portal: use the General settings tab on the Configuration page as described on Configure general settings for Linux containers.

  • Azure CLIAzure CLI:

    • 使用 az webapp config show 显示当前 Python 版本:Show the current Python version with az webapp config show:

      az webapp config show --resource-group <resource-group-name> --name <app-name> --query linuxFxVersion
      

      <resource-group-name><app-name> 替换为适合 Web 应用的名称。Replace <resource-group-name> and <app-name> with the names appropriate for your web app.

    • 使用 az webapp config set 设置 Python 版本Set the Python version with az webapp config set

      az webapp config set --resource-group <resource-group-name> --name <app-name> --linux-fx-version "PYTHON|3.7"
      
    • 使用 az webapp list-runtimes 显示 Azure 应用服务中支持的所有 Python 版本:Show all Python versions that are supported in Azure App Service with az webapp list-runtimes:

      az webapp list-runtimes --linux | grep PYTHON
      

生成自己的容器映像可以运行不受支持的 Python 版本。You can run an unsupported version of Python by building your own container image instead.

自定义生成自动化Customize build automation

在使用 Git 或 zip 包部署应用时,应用服务的生成系统(称为 Oryx)执行以下步骤:App Service's build system, called Oryx, performs the following steps when you deploy your app using Git or zip packages:

  1. 如果由 PRE_BUILD_COMMAND 设置指定,请运行预先生成的自定义脚本。Run a custom pre-build script if specified by the PRE_BUILD_COMMAND setting.
  2. 运行 pip install -r requirements.txtRun pip install -r requirements.txt. requirements.txt 文件必须存在于项目的根文件夹中。The requirements.txt file must be present in the project's root folder. 否则,生成过程将报告错误:“找不到 setup.py 或 requirements.txt;未运行 pip install。”Otherwise, the build process reports the error: "Could not find setup.py or requirements.txt; Not running pip install."
  3. 如果在存储库的根文件夹中找到了 manage.py(指示 Django 应用),则运行 manage.py collectstatic 。If manage.py is found in the root of the repository (indicating a Django app), run manage.py collectstatic. 但如果 DISABLE_COLLECTSTATIC 设置为 true,则跳过此步骤。However, if the DISABLE_COLLECTSTATIC setting is true, this step is skipped.
  4. 如果由 POST_BUILD_COMMAND 设置指定,请运行后期生成的自定义脚本。Run custom post-build script if specified by the POST_BUILD_COMMAND setting.

默认情况下,PRE_BUILD_COMMANDPOST_BUILD_COMMANDDISABLE_COLLECTSTATIC 设置为空。By default, the PRE_BUILD_COMMAND, POST_BUILD_COMMAND, and DISABLE_COLLECTSTATIC settings are empty.

  • 若要在生成 Django 应用时禁用正在运行的 collectstatic,请将 DISABLE_COLLECTSTATIC 设置设置为 true。To disable running collectstatic when building Django apps, set the DISABLE_COLLECTSTATIC setting to true.

  • 若要运行预先生成的命令,请将 PRE_BUILD_COMMAND 设置设置为包含命令(如 echo Pre-build command),或包含与项目根文件夹相对的脚本文件的路径(如 scripts/prebuild.sh)。To run pre-build commands, set the PRE_BUILD_COMMAND setting to contain either a command, such as echo Pre-build command, or a path to a script file relative to your project root, such as scripts/prebuild.sh. 所有命令都必须使用项目根文件夹的相对路径。All commands must use relative paths to the project root folder.

  • 若要运行后期生成的命令,请将 POST_BUILD_COMMAND 设置设置为包含命令(如 echo Post-build command),或包含与项目根文件夹相对的脚本文件的路径(如 scripts/postbuild.sh)。To run post-build commands, set the POST_BUILD_COMMAND setting to contain either a command, such as echo Post-build command, or a path to a script file relative to your project root, such as scripts/postbuild.sh. 所有命令都必须使用项目根文件夹的相对路径。All commands must use relative paths to the project root folder.

有关自定义生成自动化的其他设置,请参阅 Oryx 配置For additional settings that customize build automation, see Oryx configuration.

若要访问生成和部署日志,请参阅访问部署日志To access the build and deployment logs, see Access deployment logs.

若要详细了解应用服务如何在 Linux 中运行和生成 Python 应用,请参阅 Oryx 如何检测和生成 Python 应用For more information on how App Service runs and builds Python apps in Linux, see How Oryx detects and builds Python apps.

备注

PRE_BUILD_SCRIPT_PATHPOST_BUILD_SCRIPT_PATH 设置与 PRE_BUILD_COMMANDPOST_BUILD_COMMAND 相同,并且支持用于旧用途。The PRE_BUILD_SCRIPT_PATH and POST_BUILD_SCRIPT_PATH settings are identical to PRE_BUILD_COMMAND and POST_BUILD_COMMAND and are supported for legacy purposes.

如果名为 SCM_DO_BUILD_DURING_DEPLOYMENT 的设置包含 true 或 1,该设置会在部署过程中触发 Oryx 生成。A setting named SCM_DO_BUILD_DURING_DEPLOYMENT, if it contains true or 1, triggers an Oryx build happens during deployment. 当使用 git、Azure CLI 命令 az webapp up 和 Visual Studio Code 进行部署时,此设置为 true。The setting is true when deploying using git, the Azure CLI command az webapp up, and Visual Studio Code.

备注

始终在所有预先生成和后期生成脚本中使用相对路径,因为运行 Oryx 的生成容器与运行应用的运行时容器不同。Always use relative paths in all pre- and post-build scripts because the build container in which Oryx runs is different from the runtime container in which the app runs. 决不要依赖于应用项目文件夹在容器中的确切位置(例如,其位于 site/wwwroot 下)。Never rely on the exact placement of your app project folder within the container (for example, that it's placed under site/wwwroot).

将现有应用程序迁移到 AzureMigrate existing applications to Azure

可以将现有的 Web 应用程序重新部署到 Azure,如下所示:Existing web applications can be redeployed to Azure as follows:

  1. 源存储库:在适当的存储库(如 GitHub)中维护源代码,确保可以在此过程的稍后部分设置持续部署。Source repository: Maintain your source code in a suitable repository like GitHub, which enables you to set up continuous deployment later in this process.

    1. requirements.txt 文件必须位于存储库的根目录,应用服务才能自动安装必需的包。Your requirements.txt file must be at the root of your repository for App Service to automatically install the necessary packages.
  2. 数据库:如果应用依赖于数据库,则还应在 Azure 上预配必需的资源。Database: If you app depends on a database, provision the necessary resources on Azure as well. 请参阅教程:使用 PostgreSQL 部署 Django Web 应用 - 创建数据库,以了解示例。See Tutorial: Deploy a Django web app with PostgreSQL - create a database for an example.

  3. 应用服务资源:创建资源组、应用服务计划和应用服务 Web 应用来承载你的应用程序。App service resources: Create a resource group, App Service Plan, and App Service web app to host your application. 若要最轻松地实现这一点,可以使用 Azure CLI 命令 az webapp up 执行代码的初始部署,如教程:使用 PostgreSQL 部署 Django Web 应用 - 部署代码所示。You can most easily do this by doing an initial deployment of your code through the Azure CLI command az webapp up, as shown on Tutorial: Deploy a Django web app with PostgreSQL - deploy the code. 替换资源组、应用服务计划和 Web 应用的名称,使其更适合你的应用程序。Replace the names of the resource group, App Service Plan, and the web app to be more suitable for your application.

  4. 环境变量:如果应用程序需要使用任意环境变量,请创建等效的 应用服务应用程序设置Environment variables: If your application requires any environment variables, create equivalent App Service application settings. 这些应用服务设置在代码中显示为环境变量,如访问环境变量中所述。These App Service settings appear to your code as environment variables, as described on Access environment variables.

  5. 应用启动:查看后文中的 容器启动过程部分,了解应用服务如何尝试运行应用。App startup: Review the section, Container startup process later in this article to understand how App Service attempts to run your app. 默认情况下,应用服务使用 Gunicorn Web 服务器,该服务器必须能够找到应用对象或 wsgi.py 文件夹。App Service uses the Gunicorn web server by default, which must be able to find your app object or wsgi.py folder. 如有必要,可以自定义启动命令If needed, you can Customize the startup command.

  6. 自定义操作:若要在托管应用的应用服务容器内执行操作(例如 Django 数据库迁移),可以 通过 SSH 连接到容器Custom actions: To perform actions within the App Service container that hosts your app, such as Django database migrations, you can connect to the container through SSH. 有关运行 Django 数据库迁移的示例,请参阅教程:使用 PostgreSQL 部署 Django Web 应用 - 运行数据库迁移For an example of running Django database migrations, see Tutorial: Deploy a Django web app with PostgreSQL - run database migrations.

    • 使用持续部署时,可以使用生成后命令执行这些操作,如前面的自定义生成自动化所述。When using continuous deployment, you can perform those actions using post-build commands as described earlier under Customize build automation.

完成这些步骤后,你应能够将更改提交到源存储库,并将这些更新自动部署到应用服务。With these steps completed, you should be able to commit changes to your source repository and have those updates automatically deployed to App Service.

Django 应用的生产设置Production settings for Django apps

对于 Azure 应用服务之类的生产环境,Django 应用应遵循 Django 的部署清单 (djangoproject.com)。For a production environment like Azure App Service, Django apps should follow Django's Deployment checklist (djangoproject.com).

下表描述了与 Azure 相关的生产设置。The following table describes the production settings that are relevant to Azure. 这些设置在应用的 setting.py 文件中定义。These settings are defined in the app's setting.py file.

Django 设置Django setting Azure 说明Instructions for Azure
SECRET_KEY 访问作为环境变量的应用设置所述,请将值存储在应用服务设置中。Store the value in an App Service setting as described on Access app settings as environment variables. 也可以在 Azure Key Vault 中将该值存储为“机密”You can alternately store the value as a "secrete" in Azure Key Vault.
DEBUG 在应用服务上创建一个值为 0 (false) 的 DEBUG 设置,然后将该值加载为环境变量。Create a DEBUG setting on App Service with the value 0 (false), then load the value as an environment variable. 在开发环境中,创建一个值为 1 (true) 的 DEBUG 环境变量。In your development environment, create a DEBUG environment variable with the value 1 (true).
ALLOWED_HOSTS 在生产环境中,Django 要求在 settings.py 的 ALLOWED_HOSTS 数组中包含应用的 URL。In production, Django requires that you include app's URL in the ALLOWED_HOSTS array of settings.py. 可使用 os.environ['WEBSITE_HOSTNAME'] 代码在运行时检索此 URL。You can retrieve this URL at runtime with the code, os.environ['WEBSITE_HOSTNAME']. 应用服务会自动将 WEBSITE_HOSTNAME 环境变量设置为应用的 URL。App Service automatically sets the WEBSITE_HOSTNAME environment variable to the app's URL.
DATABASES 在应用服务中为数据库连接定义设置,并将这些设置加载为环境变量以填充 DATABASES 字典。Define settings in App Service for the database connection and load them as environment variables to populate the DATABASES dictionary. 也可以将值(尤其是用户名和密码)存储为 Azure Key Vault 机密You can alternately store the values (especially the username and password) as Azure Key Vault secrets.

容器特征Container characteristics

部署到应用服务时,Python 应用在应用服务 Python GitHub 存储库中定义的 Linux Docker 容器内运行。When deployed to App Service, Python apps run within a Linux Docker container that's defined in the App Service Python GitHub repository. 可以在特定于版本的目录中找到映像配置。You can find the image configurations inside the version-specific directories.

此容器具有以下特征:This container has the following characteristics:

  • 应用是结合附加参数 --bind=0.0.0.0 --timeout 600,使用 Gunicorn WSGI HTTP Server 运行的。Apps are run using the Gunicorn WSGI HTTP Server, using the additional arguments --bind=0.0.0.0 --timeout 600.

    • Gunicorn 配置概述 (docs.gunicorn.org) 中所述,可通过项目根文件夹中的 gunicorn.conf.py 文件为 Gunicorn 提供配置设置。You can provide configuration settings for Gunicorn through a gunicorn.conf.py file in the project root, as described on Gunicorn configuration overview (docs.gunicorn.org). 也可以自定义启动命令You can alternately customize the startup command.

    • 若要保护 Web 应用免遭意外或蓄意的 DDOS 攻击,请按照部署 Gunicorn (docs.gunicorn.org) 中所述,Gunicorn 在 Nginx 反向代理之后运行。To protect your web app from accidental or deliberate DDOS attacks, Gunicorn is run behind an Nginx reverse proxy as described on Deploying Gunicorn (docs.gunicorn.org).

  • 默认情况下,基础容器映像仅包含 Flask Web 框架,但容器支持符合 WSGI 规范并与 Python 3.6+ 兼容的其他框架,例如 Django。By default, the base container image includes only the Flask web framework, but the container supports other frameworks that are WSGI-compliant and compatible with Python 3.6+, such as Django.

  • 若要安装其他包(例如 Django),请在项目的根文件夹中创建 requirements.txt 文件,该文件指定直接依赖项。To install additional packages, such as Django, create a requirements.txt file in the root of your project that specifies your direct dependencies. 然后,部署项目时,应用服务会自动安装这些依赖项。App Service then installs those dependencies automatically when you deploy your project.

    requirements.txt 文件必须位于项目根文件夹中,依赖项才能安装 。The requirements.txt file must be in the project root for dependencies to be installed. 否则,生成过程将报告错误:“找不到 setup.py 或 requirements.txt;未运行 pip install。”Otherwise, the build process reports the error: "Could not find setup.py or requirements.txt; Not running pip install." 如果遇到此错误,请检查 requirements 文件的位置。If you encounter this error, check the location of your requirements file.

  • 应用服务使用 Web 应用的 URL 自动定义名为 WEBSITE_HOSTNAME 的环境变量,例如 msdocs-hello-world.chinacloudsites.cnApp Service automatically defines an environment variable named WEBSITE_HOSTNAME with the web app's URL, such as msdocs-hello-world.chinacloudsites.cn. 它还使用应用的名称定义 WEBSITE_SITE_NAME,例如 msdocs-hello-worldIt also defines WEBSITE_SITE_NAME with the name of your app, such as msdocs-hello-world.

容器启动过程Container startup process

在启动期间,Linux 上的应用服务容器将运行以下步骤:During startup, the App Service on Linux container runs the following steps:

  1. 使用自定义启动命令(如果已提供)。Use a custom startup command, if provided.
  2. 检查是否存在 Django 应用,如果已检测到,请为其启动 Gunicorn。Check for the existence of a Django app, and launch Gunicorn for it if detected.
  3. 检查是否存在 Flask 应用,如果已检测到,请为其启动 Gunicorn。Check for the existence of a Flask app, and launch Gunicorn for it if detected.
  4. 如果未找到其他任何应用,则启动容器中内置的默认应用。If no other app is found, start a default app that's built into the container.

以下部分提供了每个选项的更多详细信息。The following sections provide additional details for each option.

Django 应用Django app

对于 Django 应用,应用服务将在应用代码中查找名为 wsgi.py 的文件,然后使用以下命令运行 Gunicorn:For Django apps, App Service looks for a file named wsgi.py within your app code, and then runs Gunicorn using the following command:

# <module> is the name of the folder that contains wsgi.py
gunicorn --bind=0.0.0.0 --timeout 600 <module>.wsgi

若要更精细地控制启动命令,请使用自定义启动命令,将 <module> 替换为包含 wsgi.py 的文件夹名称,如果该模块不在项目根文件夹中,则添加 --chdir 参数。If you want more specific control over the startup command, use a custom startup command, replace <module> with the name of folder that contains wsgi.py, and add a --chdir argument if that module is not in the project root. 例如,如果 wsgi.py 位于项目根文件夹中的 knboard/backend/config 下,请使用参数 --chdir knboard/backend config.wsgiFor example, if your wsgi.py is located under knboard/backend/config from your project root, use the arguments --chdir knboard/backend config.wsgi.

若要启用生产日志记录,请按照自定义启动命令示例中所示,添加 --access-logfile--error-logfile 参数。To enable production logging, add the --access-logfile and --error-logfile parameters as shown in the examples for custom startup commands.

Flask 应用Flask app

对于 Flask,应用服务将查找名为 application.pyapp.py 的文件并启动 Gunicorn,如下所示:For Flask, App Service looks for a file named application.py or app.py and starts Gunicorn as follows:

# If application.py
gunicorn --bind=0.0.0.0 --timeout 600 application:app

# If app.py
gunicorn --bind=0.0.0.0 --timeout 600 app:app

如果主应用模块包含在不同的文件中,请对应用对象使用不同的名称;若要为 Gunicorn 提供附加的参数,请使用自定义启动命令If your main app module is contained in a different file, use a different name for the app object, or you want to provide additional arguments to Gunicorn, use a custom startup command.

默认行为Default behavior

如果应用服务找不到自定义命令、Django 应用或 Flask 应用,则它会运行位于 opt/defaultsite 文件夹中的默认只读应用。If the App Service doesn't find a custom command, a Django app, or a Flask app, then it runs a default read-only app, located in the opt/defaultsite folder. 默认应用如下所示:The default app appears as follows:

Linux 上的默认应用服务网页

自定义启动命令Customize startup command

如本文前面所述,可以通过项目根文件夹中的 gunicorn.conf.py 文件为 Gunicorn 提供配置设置,如 Gunicorn 配置概述中所述。As noted earlier in this article, you can provide configuration settings for Gunicorn through a gunicorn.conf.py file in the project root, as described on Gunicorn configuration overview.

如果此类配置不够,可以通过在启动命令文件中提供自定义启动命令或多个命令来控制容器的启动行为。If such configuration is not sufficient, you can control the container's startup behavior by providing either a custom startup command or multiple commands in a startup command file. 启动命令文件可使用你选择的任何名称,例如 startup.sh、startup.cmd、startup.txt 等 。A startup command file can use whatever name you choose, such as startup.sh, startup.cmd, startup.txt, and so on.

所有命令都必须使用项目根文件夹的相对路径。All commands must use relative paths to the project root folder.

指定启动命令或命令文件:To specify a startup command or command file:

  • Azure 门户:选择应用的“配置”页,然后选择“常规设置” 。Azure portal: select the app's Configuration page, then select General settings. 在“启动命令”字段中,输入启动命令的全文或启动命令文件的名称。In the Startup Command field, place either the full text of your startup command or the name of your startup command file. 然后,选择“保存”,应用所做的更改。Then select Save to apply the changes. 请参阅针对 Linux 容器的配置常规设置See Configure general settings for Linux containers.

  • Azure CLI:使用 az webapp config set 命令和 --startup-file 参数来设置启动命令或文件:Azure CLI: use the az webapp config set command with the --startup-file parameter to set the startup command or file:

    az webapp config set --resource-group <resource-group-name> --name <app-name> --startup-file "<custom-command>"
    

    <custom-command> 替换为启动命令的全文或启动命令文件的名称。Replace <custom-command> with either the full text of your startup command or the name of your startup command file.

应用服务将忽略处理自定义启动命令或文件时出现的任何错误,然后通过查找 Django 和 Flask 应用来继续执行其启动过程。App Service ignores any errors that occur when processing a custom startup command or file, then continues its startup process by looking for Django and Flask apps. 如果看不到预期的行为,请检查启动命令或文件是否没有错误,并且启动命令文件是否与应用代码一起部署到应用服务。If you don't see the behavior you expect, check that your startup command or file is error-free and that a startup command file is deployed to App Service along with your app code. 还可以检查诊断日志以获取更多信息。You can also check the Diagnostic logs for additional information. 还可以在 Azure 门户上查看应用的 诊断并解决问题 页面。Also check the app's Diagnose and solve problems page on the Azure portal.

示例启动命令Example startup commands

  • 添加了 Gunicorn 参数:以下示例将 --workers=4 添加到用于启动 Django 应用的 Gunicorn 命令行:Added Gunicorn arguments: The following example adds the --workers=4 to a Gunicorn command line for starting a Django app:

    # <module-path> is the relative path to the folder that contains the module
    # that contains wsgi.py; <module> is the name of the folder containing wsgi.py.
    gunicorn --bind=0.0.0.0 --timeout 600 --workers=4 --chdir <module_path> <module>.wsgi
    

    有关详细信息,请参阅运行 Gunicorn (docs.gunicorn.org)。For more information, see Running Gunicorn (docs.gunicorn.org).

  • 为 Django 启动生产日志记录:--access-logfile '-'--error-logfile '-' 参数添加到命令行:Enable production logging for Django: Add the --access-logfile '-' and --error-logfile '-' arguments to the command line:

    # '-' for the log files means stdout for --access-logfile and stderr for --error-logfile.
    gunicorn --bind=0.0.0.0 --timeout 600 --workers=4 --chdir <module_path> <module>.wsgi --access-logfile '-' --error-logfile '-'
    

    这些日志将显示在应用服务日志流中。These logs will appear in the App Service log stream.

    有关详细信息,请参阅 Gunicorn 日志记录 (docs.gunicorn.org)。For more information, see Gunicorn logging (docs.gunicorn.org).

  • 自定义 Flask 主模块:默认情况下,应用服务假定 Flask 应用的主模块是 application.py 或 app.py 。Custom Flask main module: by default, App Service assumes that a Flask app's main module is application.py or app.py. 如果主模块使用其他名称,则必须自定义启动命令。If your main module uses a different name, then you must customize the startup command. 例如,如果 Flask 应用的主模块是 hello.py,而该文件中的 Flask 应用对象名为 myapp,则命令如下所示:For example, yf you have a Flask app whose main module is hello.py and the Flask app object in that file is named myapp, then the command is as follows:

    gunicorn --bind=0.0.0.0 --timeout 600 hello:myapp
    

    如果主模块位于子文件夹(例如 website)中,请使用 --chdir 参数指定该文件夹:If your main module is in a subfolder, such as website, specify that folder with the --chdir argument:

    gunicorn --bind=0.0.0.0 --timeout 600 --chdir website hello:myapp
    
  • 使用非 Gunicorn 服务器:若要使用其他 web 服务器(如 aiohttp),请使用适当的命令作为启动命令或在启动命令文件中使用:Use a non-Gunicorn server: To use a different web server, such as aiohttp, use the appropriate command as the startup command or in the startup command file:

    python3.7 -m aiohttp.web -H localhost -P 8080 package.module:init_func
    

作为环境变量访问应用设置Access app settings as environment variables

应用设置是专门为应用存储在云中的值,如配置应用设置中所述。App settings are values stored in the cloud specifically for your app as described on Configure app settings. 这些设置可以作为环境变量提供给应用代码,并使用标准的 os.environ 模式进行访问。These settings are available to your app code as environment variables and accessed using the standard os.environ pattern.

例如,如果已创建名为 DATABASE_SERVER 的应用设置,则以下代码将检索该设置的值:For example, if you've created app setting called DATABASE_SERVER, the following code retrieves that setting's value:

db_server = os.environ['DATABASE_SERVER']

检测 HTTPS 会话Detect HTTPS session

在应用服务中,SSL 终止在网络负载均衡器上发生,因此,所有 HTTPS 请求将以未加密的 HTTP 请求形式访问你的应用。In App Service, SSL termination happens at the network load balancers, so all HTTPS requests reach your app as unencrypted HTTP requests. 如果应用逻辑需要检查用户请求是否已加密,可以检查 X-Forwarded-Proto 标头。If your app logic needs to check if the user requests are encrypted or not, inspect the X-Forwarded-Proto header.

if 'X-Forwarded-Proto' in request.headers and request.headers['X-Forwarded-Proto'] == 'https':
# Do something when HTTPS is used

使用常用 Web 框架可以访问采用标准应用模式的 X-Forwarded-* 信息。Popular web frameworks let you access the X-Forwarded-* information in your standard app pattern. CodeIgniter 中,is_https() 默认检查 X_FORWARDED_PROTO 的值。In CodeIgniter, the is_https() checks the value of X_FORWARDED_PROTO by default.

访问诊断日志Access diagnostic logs

可以访问在容器中生成的控制台日志。You can access the console logs generated from inside the container.

首先,请运行以下命令,以便启用容器日志记录功能:First, turn on container logging by running the following command:

az webapp log config --name <app-name> --resource-group <resource-group-name> --docker-container-logging filesystem

<app-name><resource-group-name> 替换为适合 Web 应用的名称。Replace <app-name> and <resource-group-name> with the names appropriate for your web app.

启用容器日志记录功能以后,请运行以下命令来查看日志流:Once container logging is turned on, run the following command to see the log stream:

az webapp log tail --name <app-name> --resource-group <resource-group-name>

如果没有立即看到控制台日志,请在 30 秒后重新查看。If you don't see console logs immediately, check again in 30 seconds.

若要随时停止日志流式处理,可键入 Ctrl+C 。To stop log streaming at any time, type Ctrl+C.

也可通过浏览器在 https://<app-name>.scm.chinacloudsites.cn/api/logs/docker 中检查日志文件。You can also inspect the log files in a browser at https://<app-name>.scm.chinacloudsites.cn/api/logs/docker.

若要通过 Azure 门户访问日志,请在应用的左侧菜单中选择“监视” > “日志流” 。To access logs through the Azure portal, select Monitoring > Log stream on the left side menu for your app.

访问部署日志Access deployment logs

当你部署代码时,应用服务会执行前面的自定义生成自动化部分所述的生成过程。When you deploy your code, App Service performs the build process described earlier in the section Customize build automation. 由于生成过程在自己的容器中运行,因此,生成日志与应用的诊断日志分开存储。Because the build runs in its own container, build logs are stored separately from the app's diagnostic logs.

通过以下步骤访问部署日志:Use the following steps to access the deployment logs:

  1. 在 Web 应用的 Azure 门户上,选择左侧菜单中的“部署” > “部署中心(预览版)”。On the Azure portal for your web app, select Deployment > Deployment Center (Preview) on the left menu.
  2. 在“日志”选项卡上,选择最新提交的“提交 ID”。On the Logs tab, select the Commit ID for the most recent commit.
  3. 在出现的“日志详细信息”页上,选择“正在运行 oryx 生成...”旁边显示的“显示日志...”链接。On the Log details page that appears, select the Show Logs... link that appears next to "Running oryx build...".

生成问题(如 requirements.txt 中不正确的依赖项)以及生成前或生成后脚本中的错误都会显示在这些日志中。Build issues such as incorrect dependencies in requirements.txt and errors in pre- or post-build scripts will appear in these logs. 如果 requirements 文件没有准确命名为 requirements.txt 或者没有出现在项目的根文件夹中,也会出现错误。Errors also appear if your requirements file is not exactly named requirements.txt or does not appear in the root folder of your project.

在浏览器中打开 SSH 会话Open SSH session in browser

若要通过容器打开直接的 SSH 会话,应用应该处于正在运行状态。To make open a direct SSH session with your container, your app should be running.

将以下 URL 粘贴到浏览器中,将 <app-name> 替换为应用名称:Paste the following URL into your browser and replace <app-name> with your app name:

https://<app-name>.scm.chinacloudsites.cn/webssh/host

如果尚未进行身份验证,则需通过要连接的 Azure 订阅进行身份验证。If you're not yet authenticated, you're required to authenticate with your Azure subscription to connect. 完成身份验证以后,可以看到一个浏览器内 shell,可以在其中的容器中运行命令。Once authenticated, you see an in-browser shell, where you can run commands inside your container.

SSH 连接

备注

/home 目录之外进行的任何更改均存储在容器本身中,在应用重启后不保留。Any changes you make outside the /home directory are stored in the container itself and don't persist beyond an app restart.

若要从本地计算机打开远程 SSH 会话,请参阅从远程 shell 打开 SSH 会话To open a remote SSH session from your local machine, see Open SSH session from remote shell.

成功连接到 SSH 会话后,应该会在窗口底部显示“已建立 SSH 连接”消息。When you're successfully connected to the SSH session, you should see the message "SSH CONNECTION ESTABLISHED" at the bottom of the window. 如果显示诸如“SSH_CONNECTION_CLOSED”之类的错误或容器重启消息,则表明可能有错误阻止应用容器启动。If you see errors such as "SSH_CONNECTION_CLOSED" or a message that the container is restarting, an error may be preventing the app container from starting. 有关调查可能存在的问题的步骤,请参阅故障排除See Troubleshooting for steps to investigate possible issues.

疑难解答Troubleshooting

应用未显示App doesn't appear

  • 部署自己的应用代码后看到默认应用。You see the default app after deploying your own app code. 之所以显示默认应用,是因为并未将应用代码部署到应用服务,或者应用服务未找到应用代码,因此运行了默认应用。The default app appears because you either haven't deployed your app code to App Service, or App Service failed to find your app code and ran the default app instead.

    • 请重启应用服务,等待 15 到 20 秒,然后再次检查应用。Restart the App Service, wait 15-20 seconds, and check the app again.

    • 请确保使用适用于 Linux 的应用服务,而不要使用基于 Windows 的实例。Be sure you're using App Service for Linux rather than a Windows-based instance. 在 Azure CLI 中运行 az webapp show --resource-group <resource-group-name> --name <app-name> --query kind 命令,对 <resource-group-name><app-name> 进行相应的替换。From the Azure CLI, run the command az webapp show --resource-group <resource-group-name> --name <app-name> --query kind, replacing <resource-group-name> and <app-name> accordingly. 应该会看到作为输出的 app,linux,否则请重新创建应用服务并选择 Linux。You should see app,linux as output; otherwise, recreate the App Service and choose Linux.

    • 使用 SSH 直接连接到应用服务容器,并验证文件是否在 site/wwwroot 下。Use SSH to connect directly to the App Service container and verify that your files exist under site/wwwroot. 如果不在,请执行以下步骤:If your files don't exist, use the following steps:

      1. 创建一个名为 SCM_DO_BUILD_DURING_DEPLOYMENT 且值为 1 的应用设置,重新部署代码,等待几分钟,然后再次尝试访问应用。Create an app setting named SCM_DO_BUILD_DURING_DEPLOYMENT with the value of 1, redeploy your code, wait a few minutes, then try to access the app again. 有关创建应用设置的详细信息,请参阅在 Azure 门户中配置应用服务应用For more information on creating app settings, see Configure an App Service app in the Azure portal.
      2. 查看部署过程,检查部署日志,更正所有错误,然后重新部署应用。Review your deployment process, check the deployment logs, correct any errors, and redeploy the app.
    • 如果这些文件存在,则表示应用服务无法识别特定的启动文件。If your files exist, then App Service wasn't able to identify your specific startup file. 检查是否按应用服务的预期方式为 DjangoFlask 构建了应用,或使用自定义启动命令Check that your app is structured as App Service expects for Django or Flask, or use a custom startup command.

  • 浏览器中显示“服务不可用”消息。You see the message "Service Unavailable" in the browser. 浏览器在等待应用服务的响应时超时,这表示应用服务已启动 Gunicorn 服务器,但应用本身未启动。The browser has timed out waiting for a response from App Service, which indicates that App Service started the Gunicorn server, but the app itself did not start. 这种情况可能表示 Gunicorn 参数不正确,或者应用代码有错误。This condition could indicate that the Gunicorn arguments are incorrect, or that there's an error in the app code.

    • 刷新浏览器,尤其是在应用服务计划中使用最低定价层的情况下。Refresh the browser, especially if you're using the lowest pricing tiers in your App Service Plan. 例如,使用免费层时,应用可能需要较长时间才能启动,并在刷新浏览器后才会做出响应。The app may take longer to start up when using free tiers, for example, and becomes responsive after you refresh the browser.

    • 检查是否按应用服务的预期方式为 DjangoFlask 构建了应用,或使用自定义启动命令Check that your app is structured as App Service expects for Django or Flask, or use a custom startup command.

    • 检查应用日志流是否有任何错误消息。Examine the app log stream for any error messages. 日志将显示应用代码中的任何错误。The logs will show any errors in the app code.

找不到 setup.py 或 requirements.txtCould not find setup.py or requirements.txt

  • 日志流显示“找不到 setup.py 或 requirements.txt;未运行 pip install。”:Oryx 生成过程找不到 requirements.txt 文件。The log stream shows "Could not find setup.py or requirements.txt; Not running pip install.": The Oryx build process failed to find your requirements.txt file.

    • 通过 SSH 连接到 Web 应用的容器,并验证 requirements.txt 的命名是否正确,以及是否就在 site/wwwroot 下。Connect to the web app's container via SSH and verify that requirements.txt is named correctly and exists directly under site/wwwroot. 如果该文件不存在,请使该文件存在于存储库中,并包含在部署中。If it doesn't exist, make site the file exists in your repository and is included in your deployment. 如果它存在于单独的文件夹中,请将其移到根文件夹下。If it exists in a separate folder, move it to the root.

其他问题Other issues

  • 在 SSH 会话中键入密码时,密码不显示:出于安全考虑,SSH 会话会在你键入密码时隐藏密码。Passwords don't appear in the SSH session when typed: For security reasons, the SSH session keeps your password hidden as you type. 但是,这些字符会被记录下来,因此,请照常键入密码,完成后按 Enter。The characters are being recorded, however, so type your password as usual and press Enter when done.

  • SSH 会话中的命令似乎已被截断:编辑器可能未对命令自动换行,但它们仍应正常运行。Commands in the SSH session appear to be cut off: The editor may not be word-wrapping commands, but they should still run correctly.

  • 静态资产未在 Django 应用中显示:确保已启用 WhiteNoise 模块Static assets don't appear in a Django app: Ensure that you have enabled the whitenoise module

  • 你看到消息“致命错误: 需要建立 SSL 连接” :检查任何用于从应用内部访问资源(如数据库)的用户名和密码。You see the message, "Fatal SSL Connection is Required": Check any usernames and passwords used to access resources (such as databases) from within the app.

后续步骤Next steps