教學課程:建置自訂映像,並從私人登錄在 App Service 中執行Tutorial: Build a custom image and run in App Service from a private registry

App Service 在 Linux 上提供內建的 Docker 映像,且支援特定的版本,例如 PHP 7.3 和 Node.js 10.14。App Service provides built-in Docker images on Linux with support for specific versions, such as PHP 7.3 and Node.js 10.14. App Service 會使用 Docker 容器技術,來裝載內建映像和自訂映像作為平台即服務。App Service uses the Docker container technology to host both built-in images and custom images as a platform as a service. 在此教學課程中,您將了解如何建置自訂映像,並在 App Service 中執行它。In this tutorial, you learn how to build a custom image and run it in App Service. 當內建的映像不包含您所選擇的語言,或當您應用程式所需的特定組態未在內建的映像中提供時,此模式相當有用。This pattern is useful when the built-in images don't include your language of choice, or when your application requires a specific configuration that isn't provided within the built-in images.

在本教學課程中,您會了解如何:In this tutorial, you learn how to:

  • 將自訂映像部署到私人容器登錄中Deploy a custom image to a private container registry
  • 在 App Service 中執行自訂映像Run the custom image in App Service
  • 設定環境變數Configure environment variables
  • 更新和重新部署映像Update and redeploy the image
  • 存取診斷記錄Access diagnostic logs
  • 使用 SSH 連線到容器Connect to the container using SSH

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶If you don't have an Azure subscription, create a free account before you begin.


若要完成本教學課程,您需要:To complete this tutorial, you need:

下載範例Download the sample

在終端機視窗中執行下列命令,將範例應用程式存放庫複製到本機電腦,然後變更為包含範例程式碼的目錄。In a terminal window, run the following command to clone the sample app repository to your local machine, then change to the directory that contains the sample code.

git clone https://github.com/Azure-Samples/docker-django-webapp-linux.git --config core.autocrlf=input
cd docker-django-webapp-linux

從 Docker 檔案建立映像Build the image from the Docker file

在 Git 存放庫中,看看 DockerfileIn the Git repository, take a look at Dockerfile. 此檔案會描述執行您應用程式所需的 Python 環境。This file describes the Python environment that is required to run your application. 此外,映像會設定 SSH 伺服器,以在容器與主機之間進行安全通訊。Additionally, the image sets up an SSH server for secure communication between the container and the host. Dockerfile 的最後一行 ENTRYPOINT ["init.sh"] 會叫用 init.sh 來啟動 SSH 服務和 Python 伺服器。The last line in the Dockerfile, ENTRYPOINT ["init.sh"], invokes init.sh to start the SSH service and Python server.

FROM python:3.4

RUN mkdir /code
ADD requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code/

# ssh
ENV SSH_PASSWD "root:Docker!"
RUN apt-get update \
        && apt-get install -y --no-install-recommends dialog \
        && apt-get update \
    && apt-get install -y --no-install-recommends openssh-server \
    && echo "$SSH_PASSWD" | chpasswd 

COPY sshd_config /etc/ssh/
COPY init.sh /usr/local/bin/
RUN chmod u+x /usr/local/bin/init.sh
EXPOSE 8000 2222

#service SSH start
#CMD ["python", "/code/manage.py", "runserver", ""]
ENTRYPOINT ["init.sh"]

使用 docker build 命令建置 Docker 映像。Build the Docker image with the docker build command.

docker build --tag mydockerimage .

測試組建運作的方式是執行 Docker 容器。Test that the build works by running the Docker container. 發出 docker run 命令,並將映像的名稱和標記傳遞給它。Issue the docker run command and pass the name and tag of the image to it. 請務必使用 -p 引數來指定連接埠。Be sure to specify the port using the -p argument.

docker run -p 8000:8000 mydockerimage

驗證 web 應用程式和容器是否會正常運作,方法是瀏覽至 http://localhost:8000Verify the web app and container are functioning correctly by browsing to http://localhost:8000.

在本機測試 Web 應用程式

使用 Azure Cloud ShellUse Azure Cloud Shell

Azure Cloud Shell 是裝載於 Azure 中的互動式殼層環境,可在瀏覽器中使用。Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. 您可以使用 Bash 或 PowerShell 搭配 Cloud Shell,與 Azure 服務共同使用。You can use either Bash or PowerShell with Cloud Shell to work with Azure services. Azure Cloud Shell 已預先安裝一些命令,可讓您執行本文提到的程式碼,而不必在本機環境上安裝任何工具。You can use the Cloud Shell preinstalled commands to run the code in this article without having to install anything on your local environment.

要啟動 Azure Cloud Shell:To start Azure Cloud Shell:

選項Option 範例/連結Example/Link
選取程式碼區塊右上角的 [試試看] 。Select Try It in the upper-right corner of a code block. 選取 [試用] 並不會自動將程式碼複製到 Cloud Shell 中。Selecting Try It doesn't automatically copy the code to Cloud Shell. Azure Cloud Shell 的試試看範例
請前往 https://shell.azure.com 或選取 [啟動 Cloud Shell] 按鈕,在瀏覽器中開啟 Cloud Shell。Go to https://shell.azure.com, or select the Launch Cloud Shell button to open Cloud Shell in your browser. 在新視窗中啟動 Cloud ShellLaunch Cloud Shell in a new window
選取 Azure 入口網站右上方功能表列上的 [Cloud Shell] 按鈕。Select the Cloud Shell button on the menu bar at the upper right in the Azure portal. Azure 入口網站中的 [Cloud Shell] 按鈕

若要在 Azure Cloud Shell 中執行本文中的程式碼:To run the code in this article in Azure Cloud Shell:

  1. 啟動 Cloud Shell。Start Cloud Shell.

  2. 選取程式碼區塊上的 [複製] 按鈕,複製程式碼。Select the Copy button on a code block to copy the code.

  3. 在 Windows 和 Linux 上選取 Ctrl+Shift+V;或在 macOS 上選取 Cmd+Shift+V,將程式碼貼到 Cloud Shell 工作階段中。Paste the code into the Cloud Shell session by selecting Ctrl+Shift+V on Windows and Linux or by selecting Cmd+Shift+V on macOS.

  4. 選取 Enter 鍵執行程式碼。Select Enter to run the code.

將應用程式部署到 AzureDeploy app to Azure

若要建立一個使用您剛才建立之映像的應用程式,請執行 Azure CLI 命令建立資源群組、推送映像,然後建立 App Service 方案 Web 應用程式來執行它。To create an app that uses the image you just created, you run Azure CLI commands that create a resource group, pushes the image, and then creates the App Service plan web app to run it.

建立資源群組Create a resource group

資源群組是一個邏輯容器,可在其中部署與管理 Azure 資源 (例如 Web 應用程式、資料庫和儲存體帳戶)。A resource group is a logical container into which Azure resources like web apps, databases, and storage accounts are deployed and managed. 例如,您可以選擇在稍候透過一個簡單的步驟刪除整個資源群組。For example, you can choose to delete the entire resource group in one simple step later.

在 Cloud Shell 中,使用 az group create 命令來建立資源群組。In the Cloud Shell, create a resource group with the az group create command. 下列範例會在「西歐」位置建立名為 myResourceGroup 的資源群組。The following example creates a resource group named myResourceGroup in the West Europe location. 若要查看基本層中 Linux 上之 App Service 的所有支援位置,請執行 az appservice list-locations --sku B1 --linux-workers-enabled 命令。To see all supported locations for App Service on Linux in Basic tier, run the az appservice list-locations --sku B1 --linux-workers-enabled command.

az group create --name myResourceGroup --location "West Europe"

您通常會在附近的區域中建立資源群組和資源。You generally create your resource group and the resources in a region near you.

當命令完成時,JSON 輸出會顯示資源群組屬性。When the command finishes, a JSON output shows you the resource group properties.

建立 Azure Container RegistryCreate an Azure Container Registry

在 Cloud Shell 中,使用 az acr create 命令來建立 Azure Container Registry。In the Cloud Shell, use the az acr create command to create an Azure Container Registry.

az acr create --name <azure-container-registry-name> --resource-group myResourceGroup --sku Basic --admin-enabled true

登入 Azure Container RegistrySign in to Azure Container Registry

若要將映像推送至登錄,您需要向私人登錄進行驗證。To push an image to the registry, you need to authenticate with the private registry. 在 Cloud Shell 中,使用 az acr show 命令從您所建立的登錄中擷取認證。In the Cloud Shell, use the az acr show command to retrieve the credentials from the registry you created.

az acr credential show --name <azure-container-registry-name>

輸出會顯示兩個密碼及使用者名稱。The output reveals two passwords along with the user name.

  "passwords": [
      "name": "password",
      "value": "{password}"
      "name": "password2",
      "value": "{password}"
  "username": "<registry-username>"

使用 docker login 命令從本機終端機視窗登入 Azure Container Registry,如下列範例所示。From your local terminal window, sign in to the Azure Container Registry using the docker login command, as shown in the following example. <azure-container-registry-name><registry-username> 取代為您的登錄值。Replace <azure-container-registry-name> and <registry-username> with values for your registry. 出現提示時,輸入上一個步驟中的其中一個密碼。When prompted, type in one of the passwords from the previous step.

docker login <azure-container-registry-name>.azurecr.io --username <registry-username>

確認登入成功。Confirm that the login succeeds.

將映像推送至 Azure Container RegistryPush image to Azure Container Registry

標記 Azure Container Registry 的本機映像。Tag your local image for the Azure Container Registry. 例如:For example:

docker tag mydockerimage <azure-container-registry-name>.azurecr.io/mydockerimage:v1.0.0

使用 docker push 命令來推送映像。Push the image by using the docker push command. 以登錄名稱再接著映像名稱和標籤來標記映像。Tag the image with the name of the registry, followed by your image name and tag.

docker push <azure-container-registry-name>.azurecr.io/mydockerimage:v1.0.0

在 Cloud Shell 中,確認推送已成功。Back in the Cloud Shell, verify that the push is successful.

az acr repository list -n <azure-container-registry-name>

您應該會取得下列輸出。You should get the following output.


建立 App Service 方案Create App Service plan

在 Cloud Shell 中,使用 az appservice plan create 命令在資源群組中建立 App Service 方案。In the Cloud Shell, create an App Service plan in the resource group with the az appservice plan create command.

下列範例會在免費定價層 (--sku F1) 和 Linux 容器 (--is-linux) 中,建立名為 myAppServicePlan 的 App Service 方案。The following example creates an App Service plan named myAppServicePlan in the Free pricing tier (--sku F1) and in a Linux container (--is-linux).

az appservice plan create --name myAppServicePlan --resource-group myResourceGroup --sku F1 --is-linux

建立 App Service 方案後,Azure CLI 會顯示類似下列範例的資訊:When the App Service plan has been created, the Azure CLI shows information similar to the following example:

  "adminSiteName": null,
  "appServicePlanName": "myAppServicePlan",
  "geoRegion": "West Europe",
  "hostingEnvironmentProfile": null,
  "id": "/subscriptions/0000-0000/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppServicePlan",
  "kind": "linux",
  "location": "West Europe",
  "maximumNumberOfWorkers": 1,
  "name": "myAppServicePlan",
  < JSON data removed for brevity. >
  "targetWorkerSizeId": 0,
  "type": "Microsoft.Web/serverfarms",
  "workerTierName": null

建立 Web 應用程式Create web app

在 Cloud Shell 中,使用 az webapp create 命令,在 myAppServicePlan App Service 方案中建立 Web 應用程式In the Cloud Shell, create a web app in the myAppServicePlan App Service plan with the az webapp create command. <app-name> 取代為唯一的應用程式名稱,將 <azure-container-registry-name> 取代為您的登錄名稱。Replace <app-name> with a unique app name, and <azure-container-registry-name> with your registry name.

az webapp create --resource-group myResourceGroup --plan myAppServicePlan --name <app-name> --deployment-container-image-name <azure-container-registry-name>.azurecr.io/mydockerimage:v1.0.0

建立 Web 應用程式後,Azure CLI 會顯示類似下列範例的輸出:When the web app has been created, the Azure CLI shows output similar to the following example:

  "availabilityState": "Normal",
  "clientAffinityEnabled": true,
  "clientCertEnabled": false,
  "cloningInfo": null,
  "containerSize": 0,
  "dailyMemoryTimeQuota": 0,
  "defaultHostName": "<app-name>.azurewebsites.net",
  "deploymentLocalGitUrl": "https://<username>@<app-name>.scm.azurewebsites.net/<app-name>.git",
  "enabled": true,
  < JSON data removed for brevity. >

在 Web 應用程式中設定登錄認證Configure registry credentials in web app

若要使 App Service 提取私人映像,它需要有關您的登錄和映像的相關資訊。For App Service to pull the private image, it needs information about your registry and image. 在 Cloud Shell 中,為他們提供 az webapp config container set 命令。In the Cloud Shell, provide them with the az webapp config container set command. 取代 <app-name><azure-container-registry-name><registry-username><password>Replace <app-name>, <azure-container-registry-name>, <registry-username>, and <password>.

az webapp config container set --name <app-name> --resource-group myResourceGroup --docker-custom-image-name <azure-container-registry-name>.azurecr.io/mydockerimage:v1.0.0 --docker-registry-server-url https://<azure-container-registry-name>.azurecr.io --docker-registry-server-user <registry-username> --docker-registry-server-password <password>


使用 Docker Hub 以外的登錄時,--docker-registry-server-url 必須格式化為 https://,後面加上登錄的完整網域名稱。When using a registry other than Docker Hub, --docker-registry-server-url must be formatted as https:// followed by the fully qualified domain name of the registry.

設定環境變數Configure environment variables

大部分的 Docker 映像會使用自訂環境變數,例如 80 以外的連接埠。Most Docker images use custom environment variables, such as a port other than 80. 可告訴 App Service 您映像所使用的連接埠,方法是使用 WEBSITES_PORT 應用程式設定。You tell App Service about the port that your image uses by using the WEBSITES_PORT app setting. 本教學課程中的 Python 範例 GitHub 頁面說明您必須將 WEBSITES_PORT 設定為 8000The GitHub page for the Python sample in this tutorial shows that you need to set WEBSITES_PORT to 8000.

若要設定應用程式的設定,請在 Cloud Shell 中使用 az webapp config appsettings set 命令。To set app settings, use the az webapp config appsettings set command in the Cloud Shell. 應用程式設定為區分大小寫和空格分隔。App settings are case-sensitive and space-separated.

az webapp config appsettings set --resource-group myResourceGroup --name <app-name> --settings WEBSITES_PORT=8000

測試 Web 應用程式Test the web app

瀏覽至 Web 應用程式以確認它可運作 (http://<app-name>.azurewebsites.net)。Verify that the web app works by browsing to it (http://<app-name>.azurewebsites.net).


第一次存取應用程式時,可能需要一些時間,因為 App Service 必須提取整個映像。The first time you access the app, it may take some time because App Service needs to pull the entire image. 如果瀏覽器逾時,只需重新整理頁面即可。If the browser times out, just refresh the page.

測試 web 應用程式連接埠設定

變更 Web 應用程式並重新部署Change web app and redeploy

在您的本機 Git 存放庫中,開啟 app/templates/app/index.html。In your local Git repository, open app/templates/app/index.html. 找出第一個 HTML 元素,並將它加以變更。Locate the first HTML element and change it to.

<nav class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
      <div class="navbar-header">
        <a class="navbar-brand" href="#">Azure App Service - Updated Here!</a>

一旦您修改了 Python 檔案並加以儲存後,必須重建並推送新的 Docker 映像。Once you've modified the Python file and saved it, you must rebuild and push the new Docker image. 接著,重新啟動 Web 應用程式,變更才會生效。Then restart the web app for the changes to take effect. 使用您先前已在本教學課程中使用的相同命令。Use the same commands that you have previously used in this tutorial. 您可以參考從 Docker 檔案建立映像將映像推送至 Azure Container RegistryYou can refer to Build the image from the Docker file and Push image to Azure Container Registry. 遵循測試 Web 應用程式中的指示來測試 web 應用程式。Test the web app by following the instructions in Test the web app.

存取診斷記錄Access diagnostic logs

您可以存取從容器產生的主控台記錄。You can access the console logs generated from inside the container. 請先在 Cloud Shell 中執行下列命令來開啟容器記錄:First, turn on container logging by running the following command in the Cloud Shell:

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

開啟容器記錄後,請執行下列命令來查看記錄資料流:Once container logging is turned on, run the following command to see the log stream:

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

如果您沒有立即看到主控台記錄,請在 30 秒後再查看。If you don't see console logs immediately, check again in 30 seconds.


您也可以在瀏覽器中的 https://<app-name>.scm.azurewebsites.net/api/logs/docker 檢查記錄檔。You can also inspect the log files from the browser at https://<app-name>.scm.azurewebsites.net/api/logs/docker.

若要隨時停止記錄資料流,請輸入 Ctrl+CTo stop log streaming at any time, type Ctrl+C.

啟用 SSH 連線Enable SSH connections

SSH 可讓容器和用戶端之間進行安全通訊。SSH enables secure communication between a container and a client. 若要啟用與容器的 SSH 連線,則必須設定它的自訂映像。To enable SSH connection to your container, your custom image must be configured for it. 讓我們看一下已經具有必要設定的範例存放庫。Let's take a look at the sample repository that already has the necessary configuration.

  • Dockerfile 中,下列程式碼會安裝 SSH 伺服器,並也會設定登入認證。In the Dockerfile, the following code installs the SSH server and also sets the sign-in credentials.

    ENV SSH_PASSWD "root:Docker!"
    RUN apt-get update \
            && apt-get install -y --no-install-recommends dialog \
            && apt-get update \
      && apt-get install -y --no-install-recommends openssh-server \
      && echo "$SSH_PASSWD" | chpasswd 


    此設定不允許容器的外部連線。This configuration does not allow external connections to the container. SSH 只能透過 Kudu/SCM 站台提供。SSH is available only through the Kudu/SCM Site. Kudu/SCM 站台會向 Azure 帳戶進行驗證。The Kudu/SCM site is authenticated with your Azure account.

  • Dockerfile 會將存放庫中的 sshd_config 檔案複製到 /etc/ssh/ 目錄。The Dockerfile copies the sshd_config file in the repository to the /etc/ssh/ directory.

    COPY sshd_config /etc/ssh/
  • Dockerfile 會公開容器中的連接埠 2222。The Dockerfile exposes port 2222 in the container. 它是供內部使用的連接埠,只有私人虛擬網路之橋接網路內的容器可以存取。It is an internal port accessible only by containers within the bridge network of a private virtual network.

    EXPOSE 8000 2222
  • 輸入指令碼會啟動 SSH 伺服器。The entry script starts the SSH server.

    service ssh start

開啟對容器的 SSH 連線Open SSH connection to container

SSH 連線只能透過 Kudu 站台提供,可在 https://<app-name>.scm.azurewebsites.net 存取。SSH connection is available only through the Kudu site, which is accessible at https://<app-name>.scm.azurewebsites.net.

若要連線,請瀏覽至 https://<app-name>.scm.azurewebsites.net/webssh/host 並以您的 Azure 帳戶登入。To connect, browse to https://<app-name>.scm.azurewebsites.net/webssh/host and sign in with your Azure account.

然後,系統會將您重新導向至一個顯示互動式主控台的頁面。You are then redirected to a page displaying an interactive console.

您需要確認特定應用程式正在容器中執行。You may wish to verify that certain applications are running in the container. 若要檢查容器並確認執行的流程,在提示字元提出 top 命令。To inspect the container and verify running processes, issue the top command at the prompt.


top 命令會公開容器中所有執行中的程序。The top command exposes all running processes in a container.

 1 root      20   0  945616  35372  15348 S  0.0  2.1   0:04.63 node
20 root      20   0   55180   2776   2516 S  0.0  0.2   0:00.00 sshd
42 root      20   0  944596  33340  15352 S  0.0  1.9   0:05.80 node /opt/s+
56 root      20   0   59812   5244   4512 S  0.0  0.3   0:00.93 sshd
58 root      20   0   20228   3128   2664 S  0.0  0.2   0:00.00 bash
62 root      20   0   21916   2272   1944 S  0.0  0.1   0:03.15 top
63 root      20   0   59812   5344   4612 S  0.0  0.3   0:00.03 sshd
65 root      20   0   20228   3140   2672 S  0.0  0.2   0:00.00 bash
71 root      20   0   59812   5380   4648 S  0.0  0.3   0:00.02 sshd
73 root      20   0   20228   3160   2696 S  0.0  0.2   0:00.00 bash
77 root      20   0   21920   2304   1972 R  0.0  0.1   0:00.00 top

恭喜!Congratulations! 您已在 App Service 中設定自訂的 Linux 容器。You've configured a custom Linux container in App Service.

清除部署Clean up deployment

在執行過範例指令碼之後,您可以使用下列命令來移除資源群組和所有與其相關聯的資源。After the sample script has been run, the following command can be used to remove the resource group and all resources associated with it.

az group delete --name myResourceGroup

後續步驟Next steps

您已了解如何︰What you learned:

  • 將自訂映像部署到私人容器登錄中Deploy a custom image to a private container registry
  • 在 App Service 中執行自訂映像Run the custom image in App Service
  • 設定環境變數Configure environment variables
  • 更新和重新部署映像Update and redeploy the image
  • 存取診斷記錄Access diagnostic logs
  • 使用 SSH 連線到容器Connect to the container using SSH

前往下一個教學課程,了解如何將自訂的 DNS 名稱對應至應用程式。Advance to the next tutorial to learn how to map a custom DNS name to your app.

或者,查看其他資源:Or, check out other resources: