共用方式為


部署 Flask 或 FastAPI 網頁應用程式於 Azure 容器應用服務

這個教學會教你如何將 Python FlaskFastAPI 網頁應用程式容器化,並部署到 Azure Container Apps。 Azure Container Apps 採用 Docker容器技術來承載內建映像檔與自訂映像檔。 欲了解更多關於在Azure中使用容器的資訊,請參見 Comparing Azure container options

在這個教學中,你使用 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", "--config", "gunicorn.conf.py", "app:app"]

這個例子使用 50505 作為容器的內部埠,但你也可以使用任何空閒的埠。

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

Flask==3.1.0
gunicorn

設定 gunicorn

你可以用 gunicorn.conf.py 檔案來設定 Gunicorn。 當 gunicorn.conf.py 檔案位於你執行gunicorn的同一個目錄時,你不需要在 ENTRYPOINT 的 or CMD 指令中指定它的位置。 如需指定組態檔的詳細資訊,請參閱 Gunicorn 設定

在此教學中,建議的設定檔會根據可用 CPU 核心數量來設定 Gunicorn 增加工作者數量。 如需 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

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

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

在本機建置並執行映像

在本機建置映像。

docker build --tag flask-demo .

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

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

在瀏覽器開啟 http://localhost:5000 即可看到本地執行的網頁應用程式。

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

部署網路應用程式至 Azure

要部署 Docker 映像檔到 Azure Container Apps,請使用 az containerapp up 指令。 (下列命令適用於 Bash 命令列。 根據其他 shell 的需要適當變更延續字元(\)。

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

部署結束後,你會有一個資源群組,裡面包含以下資源:

  • Azure 容器登錄服務
  • 容器應用程式環境
  • 執行 Web 應用程式映像的容器應用程式
  • Log Analytics 工作區

指令的輸出 az containerapp up 會包含已部署應用程式的網址。 在瀏覽器中開啟網址,可以看到網頁應用程式在 Azure 上運行。 URL 看起來像是 https://web-aca-app.<generated-text>.<location-info>.azurecontainerapps.io,其中 <generated-text><location-info> 是您部署中的唯一項目。

進行更新並重新部署

更新程式碼後,再執行一次之前的 az containerapp up 指令。 這個指令會重建映像並重新部署到 Azure Container Apps。 當你再次執行該指令時,它會偵測到資源群組和應用程式已經存在,並只更新容器應用程式。

在較複雜的更新情境中,你可以同時使用 az acr buildaz containerapp update 指令來重新部署容器應用程式。

收拾

你在這個教學中建立的所有 Azure 資源都放在同一個資源群組裡。 移除資源群組即移除該資源群組中的所有資源。 這是最快的方法來移除應用程式所用的所有 Azure 資源。

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

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

你也可以在 Azure portal或在 Visual Studio Code 中使用 Azure工具擴充功能移除該群組。

後續步驟

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