运行 Init 容器以在容器组中执行设置任务Run an init container for setup tasks in a container group

Azure 容器实例支持容器组中的 Init 容器。Azure Container Instances supports init containers in a container group. Init 容器会在单个或多个应用程序容器启动之前运行完毕。Init containers run to completion before the application container or containers start. 可以使用一个或多个 Init 容器为应用容器执行初始化逻辑(如设置帐户、运行安装脚本或配置数据库),这一点与 Kubernetes Init 容器类似。Similar to Kubernetes init containers, use one or more init containers to perform initialization logic for your app containers, such as setting accounts, running setup scripts, or configuring databases.

本文介绍如何使用 Azure 资源管理器模板配置包含 Init 容器的容器组。This article shows how to use an Azure Resource Manager template to configure a container group with an init container.

使用须知Things to know

  • API 版本 - 至少需要有 Azure 容器实例 API 版本 2019-12-01 才能部署 Init 容器。API version - You need at least Azure Container Instances API version 2019-12-01 to deploy init containers. 使用 YAML 文件资源管理器模板中的 initContainers 属性进行部署。Deploy using an initContainers property in a YAML file or a Resource Manager template.

  • 执行顺序 - Init 容器按模板中指定的顺序执行,并且是在其他容器之前执行。Order of execution - Init containers are executed in the order specified in the template, and before other containers. 默认情况下,最多可以为每个容器组指定 59 个 Init 容器。By default, you can specify a maximum of 59 init containers per container group. 组中必须至少有一个非 Init 容器。At least one non-init container must be in the group.

  • 主机环境 - Init 容器与组中的其余容器在同一硬件上运行。Host environment - Init containers run on the same hardware as the rest of the containers in the group.

  • 资源 - 不为 Init 容器指定资源。Resources - You don't specify resources for init containers. 它们被授予可供容器组使用的全部资源(例如,CPU 和内存)。They are granted the total resources such as CPUs and memory available to the container group. 当 Init 容器运行时,组中不会运行其他容器。While an init container runs, no other containers run in the group.

  • 支持的属性 - Init 容器可以使用组属性(如卷、机密和托管标识)。Supported properties - Init containers can use group properties such as volumes, secrets, and managed identities. 但是,它们不能使用端口或 IP 地址(如果已为容器组配置)。However, they can't use ports or an IP address if configured for the container group.

  • 重启策略 - 每个 Init 容器必须成功退出,然后该组中的下一个容器才能启动。Restart policy - Each init container must exit successfully before the next container in the group starts. 如果 Init 容器未成功退出,则其重启操作取决于为该组配置的重启策略If an init container doesn't exit successfully, its restart action depends on the restart policy configured for the group:

    组中的策略Policy in group Init 中的策略Policy in init
    AlwaysAlways OnFailureOnFailure
    OnFailureOnFailure OnFailureOnFailure
    从不Never 从不Never
  • 费用 - 容器组在首次部署 Init 容器时会产生费用。Charges - The container group incurs charges from the first deployment of an init container.

资源管理器模板示例Resource Manager template example

首先将以下 JSON 复制到一个名为 azuredeploy.json 的新文件中。Start by copying the following JSON into a new file named azuredeploy.json. 该模板将设置一个包含一个 Init 容器和两个应用程序容器的容器组:The template sets up a container group with one init container and two application containers:

  • init1 容器从 Docker Hub 运行 busybox 映像。The init1 container runs the busybox image from Docker Hub. 它会休眠 60 秒,然后将命令行字符串写入 emptyDir 卷中的文件。It sleeps for 60 seconds and then writes a command-line string to a file in an emptyDir volume.

  • 两个应用程序容器均运行 Microsoft aci-wordcount 容器映像:Both application containers run the Microsoft aci-wordcount container image:

    • hamlet 容器以默认配置运行 wordcount 应用,计算莎士比亚戏剧“哈姆雷特”中的单词频率。The hamlet container runs the wordcount app in its default configuration, counting word frequencies in Shakespeare's play Hamlet.
    • juliet 应用容器将从 emptDir 卷读取命令行字符串,这样就可以改为对莎士比亚的“罗密欧和朱丽叶”运行 wordcount 应用。The juliet app container reads the command-line string from the emptDir volume to run the wordcount app instead on Shakespeare's Romeo and Juliet.

有关如何使用 aci-wordcount 映像的详细信息和示例,请参阅在容器实例中设置环境变量For more information and examples using the aci-wordcount image, see Set environment variables in container instances.

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
      "containerGroupName": {
        "type": "string",
        "defaultValue": "myContainerGroup",
        "metadata": {
          "description": "Container Group name."
        }
      }
    },
    "resources": [
        {
            "name": "[parameters('containerGroupName')]",
            "type": "Microsoft.ContainerInstance/containerGroups",
            "apiVersion": "2019-12-01",
            "location": "[resourceGroup().location]",
            "properties": {
                "sku": "Standard",
                "initContainers": [
                {
                    "name": "init1",
                    "properties": {
                        "image": "busybox",
                        "environmentVariables": [],
                        "volumeMounts": [
                            {
                                "name": "emptydir1",
                                "mountPath": "/mnt/emptydir"
                            }
                        ],
                         "command": [
                            "/bin/sh",
                            "-c",
                            "sleep 60; echo python wordcount.py http://shakespeare.mit.edu/romeo_juliet/full.html > /mnt/emptydir/command_line.txt"
                        ]
                    }
                }
            ], 
                "containers": [
                    {
                        "name": "hamlet",
                        "properties": {
                            "image": "mcr.microsoft.com/azuredocs/aci-wordcount",
                            "volumeMounts": [
                            {
                                "name": "emptydir1",
                                "mountPath": "/mnt/emptydir"
                            }
                        ],
                            "environmentVariables": [
                             {
                                "name": "NumWords",
                                "value": "3"
                             },
                             {  "name": "MinLength",
                                "value": "5"
                             }
                            ],
                            "resources": {
                                "requests": {
                                    "memoryInGB": 1.0,
                                    "cpu": 1
                                }
                            }
                        }
                    },
                    {
                        "name": "juliet",
                        "properties": {
                            "image": "mcr.microsoft.com/azuredocs/aci-wordcount",
                            "volumeMounts": [
                            {
                                "name": "emptydir1",
                                "mountPath": "/mnt/emptydir"
                            }
                            ],
                            "command": [
                                "/bin/sh",
                                "-c",
                                "$(cat /mnt/emptydir/command_line.txt)"
                            ],
                            "environmentVariables": [
                             {
                                "name": "NumWords",
                                "value": "3"
                             },
                             {  "name": "MinLength",
                                "value": "5"
                             }
                            ],
                            "resources": {
                                "requests": {
                                    "memoryInGB": 1.0,
                                    "cpu": 1
                                }
                            }
                        }
                    }
                ],
                "restartPolicy": "OnFailure",
                "osType": "Linux",
                "volumes": [
                    {
                        "name": "emptydir1",
                        "emptyDir": {}
                    }
                ]           
            },
            "tags": {}
        }
    ]
}

部署模板Deploy the template

使用“az group create”命令创建资源组。Create a resource group with the az group create command.

az group create --name myResourceGroup --location chinaeast2

使用 az deployment group create 命令部署模板。Deploy the template with the az deployment group create command.

az deployment group create \
  --resource-group myResourceGroup \
  --template-file azuredeploy.json

在包含 Init 容器的组中,由于完成单个或多个 Init 容器需要时间,因此部署时间会增加。In a group with an init container, the deployment time is increased because of the time it takes for the init container or containers to complete.

查看容器日志View container logs

若要验证 Init 容器是否已成功运行,请使用 az container logs 命令查看应用容器的日志输出。To verify the init container ran successfully, view the log output of the app containers using the az container logs command. --container-name 参数指定从中拉取日志的容器。The --container-name argument specifies the container from which to pull logs. 在此示例中,可拉取 hamlet 和 juliet 容器的日志,其中显示了不同的命令输出:In this example, pull the logs for the hamlet and juliet containers, which show different command output:

az container logs \
  --resource-group myResourceGroup \
  --name myContainerGroup \
  --container-name hamlet

输出:Output:

[('HAMLET', 386), ('HORATIO', 127), ('CLAUDIUS', 120)]
az container logs \
  --resource-group myResourceGroup \
  --name myContainerGroup \
  --container-name juliet

输出:Output:

[('ROMEO', 177), ('JULIET', 134), ('CAPULET', 119)]

后续步骤Next steps

Init 容器可帮助你对应用程序容器执行设置和初始化任务。Init containers help you perform setup and initialization tasks for your application containers. 若要详细了解如何运行基于任务的容器,请参阅使用重启策略运行容器化任务For more information about running task-based containers, see Run containerized tasks with restart policies.

Azure 容器实例提供了其他用于修改应用程序容器行为的选项。Azure Container Instances provides other options to modify the behavior of application containers. 示例包括:Examples include: