在 Azure Container Apps 上部署 Flask 或 FastAPI Web 應用程式

本教學課程說明如何容器化 Python Flask FastAPI Web 應用程式,並將其部署至 Azure Container Apps 。 Azure Container Apps 使用 Docker 容器技術來裝載內建映射和自訂映射。 如需在 Azure 中使用容器的詳細資訊,請參閱 比較 Azure 容器選項

在本教學課程中,您會使用 Docker CLI Azure CLI 來建立 Docker 映射,並將其部署至 Azure Container Apps。 您也可以使用 Visual Studio Code Azure 工具擴充功能 進行部署。

必要條件

若要完成本教學課程,您需要:

取得範例程式碼

在您的本機環境中,取得程式碼。

git clone https://github.com/Azure-Samples/msdocs-python-flask-webapp-quickstart.git

新增 Dockerfile 和 .dockerignore 檔案

新增 Dockerfile 以指示 Docker 如何建置映射。 Dockerfile 會指定 Gunicorn 的使用,這是將 Web 要求轉送至 Flask 和 FastAPI 架構的生產層級 Web 服務器。 ENTRYPOINT 和 CMD 命令會指示 Gunicorn 處理應用程式物件的要求。

# syntax=docker/dockerfile:1

FROM python:3.11

WORKDIR /code

COPY requirements.txt .

RUN pip3 install -r requirements.txt

COPY . .

EXPOSE 50505

ENTRYPOINT ["gunicorn", "app:app"]

50505 用於此範例中的容器埠(內部),但您可以使用任何免費埠。

請檢查 requirements.txt 檔案,確定它包含 gunicorn

Flask==2.2.2
gunicorn
Werkzeug==2.2.2

新增 .dockerignore 檔案,以從映射中排除不必要的檔案。

.git*
**/*.pyc
.venv/

設定 gunicorn

Gunicorn 可以使用 gunicorn.conf.py 檔案進行設定。 當 gunicorn.conf.py 檔案位於執行所在的 gunicorn 相同目錄中時,您不需要在 Dockerfile 的 或 CMD 指令 ENTRYPOINT 指定其位置。 如需指定組態檔的詳細資訊,請參閱 Gunicorn 設定

在本教學課程中,建議的組態檔會設定 GUnicorn,根據可用的 CPU 核心數目來增加其背景工作角色數目。 如需 gunicorn.conf.py 檔案設定的詳細資訊 ,請參閱 Gunicorn 組態

# Gunicorn configuration file
import multiprocessing

max_requests = 1000
max_requests_jitter = 50

log_file = "-"

bind = "0.0.0.0:50505"

workers = (multiprocessing.cpu_count() * 2) + 1
threads = workers

timeout = 120

在本機建置並執行映射

在本機建置映射。

docker build --tag flask-demo .

在 Docker 容器中本機執行映射。

docker run --detach --publish 5000:50505 flask-demo

http://localhost:5000在瀏覽器中開啟 URL,以查看在本機執行的 Web 應用程式。

選項 --detach 會在背景中執行容器。 選項 --publish 會將容器埠對應至主機上的埠。 主機埠 (external) 是配對中的第一個埠,而容器埠 (internal) 則是第二個。 如需詳細資訊,請參閱 Docker 執行參考

將 Web 應用程式部署至 Azure

若要將 Docker 映射部署至 Azure Container Apps,請使用 az containerapp up 命令。 (Bash 殼層會顯示下列命令。 視需要變更其他殼層的接續字元 ( \ )。

az containerapp up \
  --resource-group web-flask-aca-rg --name web-aca-app \
  --ingress external --target-port 50505 --source .

部署完成時,您有一個資源群組,其中包含下列資源:

  • Azure Container Registry
  • 容器應用程式環境
  • 執行 Web 應用程式映射的容器應用程式
  • Log Analytics 工作區

已部署應用程式的 URL 位於命令的輸出中 az containerapp up 。 在瀏覽器中開啟 URL,以查看在 Azure 中執行的 Web 應用程式。 URL 的格式如下所示 https://web-aca-app.<generated-text>.<location-info>.azurecontainerapps.io ,其中 <generated-text><location-info> 對您的部署而言是唯一的。

進行更新並重新部署

進行程式碼更新之後,您可以再次執行上一 az containerapp up 個命令,以重建映射並將其重新部署至 Azure Container Apps。 再次執行 命令會考慮資源群組和應用程式已經存在,並只更新容器應用程式。

在更複雜的更新案例中,您可以使用 az acr build az containerapp update 命令一起重新部署 ,以更新容器應用程式。

清理

本教學課程中建立的所有 Azure 資源都位於相同的資源群組中。 移除資源群組會移除資源群組中的所有資源,這是移除應用程式所用所有 Azure 資源最快的方式。

若要移除資源,請使用 az group delete 命令。

az group delete --name web-flask-aca-rg

您也可以移除Azure 入口網站 或 Visual Studio Code 和 Azure Tools Extension 中的 群組 。

下一步

如需詳細資訊,請參閱以下資源: