您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

适用于 .NET 的 Azure 容器实例库Azure Container Instances libraries for .NET

使用适用于 .NET 的 Microsoft Azure 容器实例库来创建和管理 Azure 容器实例。Use the Microsoft Azure Container Instances libraries for .NET to create and manage Azure container instances. 请阅读 Azure 容器实例概述,了解详细信息。Learn more by reading the Azure Container Instances overview.

管理库Management library

使用管理库可在 Azure 中创建和管理 Azure 容器实例。Use the management library to create and manage Azure container instances in Azure.

直接从 Visual Studio 包管理器控制台或使用 .NET Core CLI 安装 NuGet 包Install the NuGet package directly from the Visual Studio Package Manager console or with the .NET Core CLI.

Visual Studio 包管理器Visual Studio Package Manager

Install-Package Microsoft.Azure.Management.ContainerInstance.Fluent
dotnet add package Microsoft.Azure.Management.ContainerInstance.Fluent

示例源Example source

若要在上下文中查看以下代码示例,可以在以下 GitHub 存储库中找到它们:If you'd like to see the following code examples in context, you can find them in the following GitHub repository:

Azure-Samples/aci-docs-sample-dotnetAzure-Samples/aci-docs-sample-dotnet

身份验证Authentication

对 SDK 客户端进行身份验证的最简单方法之一是使用基于文件的身份验证One of the easiest ways to authenticate SDK clients is with file-based authentication. 基于文件的身份验证会在实例化 IAzure 客户端对象时分析凭据文件,然后该对象将在向 Azure 进行身份验证时使用这些凭据。File-based authentication parses a credentials file when instantiating the IAzure client object, which then uses those credentials when authenticating with Azure. 若要使用基于文件的身份验证,请执行以下操作:To use file-based authentication:

  1. 使用 Azure CLICloud Shell 创建凭据文件:Create a credentials file with the Azure CLI or Cloud Shell:

    az ad sp create-for-rbac --sdk-auth > my.azureauth

    如果使用 Cloud Shell 生成凭据文件,请将其内容复制到 .NET 应用程序能够访问的本地文件中。If you use the Cloud Shell to generate the credentials file, copy its contents into a local file that your .NET application can access.

  2. AZURE_AUTH_LOCATION 环境变量设置为生成的凭据文件的完整路径。Set the AZURE_AUTH_LOCATION environment variable to the full path of the generated credentials file. 例如(在 Bash shell 中):For example (in the Bash shell):

    export AZURE_AUTH_LOCATION=/home/yourusername/my.azureauth
    

在创建凭据文件并填充AZURE_AUTH_LOCATION环境变量后,请使用 Azure.Authenticate 方法来初始化 IAzure 客户端对象。Once you've created the credentials file and populated the AZURE_AUTH_LOCATION environment variable, use the Azure.Authenticate method to initialize the IAzure client object. 该示例项目首先获取 AZURE_AUTH_LOCATION 值,然后调用一个方法,该方法将返回初始化的 IAzure 客户端对象:The example project first obtains the AZURE_AUTH_LOCATION value, then calls a method that returns an initialized IAzure client object:

// Set the AZURE_AUTH_LOCATION environment variable with the full
// path to an auth file. Create an auth file with the Azure CLI:
// az ad sp create-for-rbac --sdk-auth > my.azureauth
string authFilePath = Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION");

// Authenticate with Azure
IAzure azure = GetAzureContext(authFilePath);

来自示例应用程序的此方法将返回初始化的 IAzure 实例,然后该示例将作为第一个参数传递到示例中的所有其他方法:This method from the sample application returns the initialized IAzure instance, which is then passed as the first parameter to all other methods in the sample:

/// <summary>
/// Returns an authenticated Azure context using the credentials in the
/// specified auth file.
/// </summary>
/// <param name="authFilePath">The full path to a credentials file on the local filesystem.</param>
/// <returns>Authenticated IAzure context.</returns>
private static IAzure GetAzureContext(string authFilePath)
{            
    IAzure azure;
    ISubscription sub;

    try
    {
        Console.WriteLine($"Authenticating with Azure using credentials in file at {authFilePath}");

        azure = Azure.Authenticate(authFilePath).WithDefaultSubscription();
        sub = azure.GetCurrentSubscription();

        Console.WriteLine($"Authenticated with subscription '{sub.DisplayName}' (ID: {sub.SubscriptionId})");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"\nFailed to authenticate:\n{ex.Message}");

        if (String.IsNullOrEmpty(authFilePath))
        {
            Console.WriteLine("Have you set the AZURE_AUTH_LOCATION environment variable?");
        }

        throw;
    }

    return azure;
}

若要更详细地了解用于 Azure 的 .NET 管理库中提供的身份验证方法,请参阅用于 .NET 的 Azure 管理库中的身份验证For more details about the available authentication methods in the .NET management libraries for Azure, see Authentication in Azure Management Libraries for .NET.

创建容器组 - 单个容器Create container group - single container

此示例创建包含单个容器的容器组。This example creates a container group with a single container.

/// <summary>
/// Creates a container group with a single container.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group in which to create the container group.</param>
/// <param name="containerGroupName">The name of the container group to create.</param>
/// <param name="containerImage">The container image name and tag, for example 'microsoft\aci-helloworld:latest'.</param>
private static void CreateContainerGroup(IAzure azure,
                                         string resourceGroupName, 
                                         string containerGroupName, 
                                         string containerImage)
{
    Console.WriteLine($"\nCreating container group '{containerGroupName}'...");

    // Get the resource group's region
    IResourceGroup resGroup = azure.ResourceGroups.GetByName(resourceGroupName);
    Region azureRegion = resGroup.Region;

    // Create the container group
    var containerGroup = azure.ContainerGroups.Define(containerGroupName)
        .WithRegion(azureRegion)
        .WithExistingResourceGroup(resourceGroupName)
        .WithLinux()
        .WithPublicImageRegistryOnly()
        .WithoutVolume()
        .DefineContainerInstance(containerGroupName + "-1")
            .WithImage(containerImage)
            .WithExternalTcpPort(80)
            .WithCpuCoreCount(1.0)
            .WithMemorySizeInGB(1)
            .Attach()
        .WithDnsPrefix(containerGroupName)
        .Create();

    Console.WriteLine($"Once DNS has propagated, container group '{containerGroup.Name}' will be reachable at http://{containerGroup.Fqdn}");
}

创建容器组 - 多个容器Create container group - multiple containers

此示例创建包含两个容器的容器组:应用程序容器和挎斗容器。This example creates a container group with two containers: an application container and a sidecar container.

/// <summary>
/// Creates a container group with two containers in the specified resource group.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group in which to create the container group.</param>
/// <param name="containerGroupName">The name of the container group to create.</param>
/// <param name="containerImage1">The first container image name and tag, for example 'microsoft\aci-helloworld:latest'.</param>
/// <param name="containerImage2">The second container image name and tag, for example 'microsoft\aci-tutorial-sidecar:latest'.</param>
private static void CreateContainerGroupMulti(IAzure azure,
                                              string resourceGroupName,
                                              string containerGroupName, 
                                              string containerImage1, 
                                              string containerImage2)
{
    Console.WriteLine($"\nCreating multi-container container group '{containerGroupName}'...");

    // Get the resource group's region
    IResourceGroup resGroup = azure.ResourceGroups.GetByName(resourceGroupName);
    Region azureRegion = resGroup.Region;

    // Create the container group
    var containerGroup = azure.ContainerGroups.Define(containerGroupName)
        .WithRegion(azureRegion)
        .WithExistingResourceGroup(resourceGroupName)
        .WithLinux()
        .WithPublicImageRegistryOnly()
        .WithoutVolume()
        .DefineContainerInstance(containerGroupName + "-1")
            .WithImage(containerImage1)
            .WithExternalTcpPort(80)
            .WithCpuCoreCount(0.5)
            .WithMemorySizeInGB(1)
            .Attach()
        .DefineContainerInstance(containerGroupName + "-2")
            .WithImage(containerImage2)
            .WithoutPorts()
            .WithCpuCoreCount(0.5)
            .WithMemorySizeInGB(1)
            .Attach()
        .WithDnsPrefix(containerGroupName)
        .Create();

    Console.WriteLine($"Once DNS has propagated, container group '{containerGroup.Name}' will be reachable at http://{containerGroup.Fqdn}");
}

通过轮询进行异步容器创建Asynchronous container create with polling

此示例使用异步创建方法创建包含单个容器的容器组。This example creates a container group with a single container using the async create method. 然后,它将在 Azure 中轮询该容器组,并且会输出容器组的状态,直到其状态为“Running”。It then polls Azure for the container group, and outputs the container group's status until its state is "Running."

/// <summary>
/// Creates a container group with a single container asynchronously, and
/// polls its status until its state is 'Running'.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group in which to create the container group.</param>
/// <param name="containerGroupName">The name of the container group to create.</param>
/// <param name="containerImage">The container image name and tag, for example 'microsoft\aci-helloworld:latest'.</param>
private static void CreateContainerGroupWithPolling(IAzure azure,
                                         string resourceGroupName, 
                                         string containerGroupName, 
                                         string containerImage)
{
    Console.WriteLine($"\nCreating container group '{containerGroupName}'...");

    // Get the resource group's region
    IResourceGroup resGroup = azure.ResourceGroups.GetByName(resourceGroupName);
    Region azureRegion = resGroup.Region;

    // Create the container group using a fire-and-forget task
    Task.Run(() =>

        azure.ContainerGroups.Define(containerGroupName)
            .WithRegion(azureRegion)
            .WithExistingResourceGroup(resourceGroupName)
            .WithLinux()
            .WithPublicImageRegistryOnly()
            .WithoutVolume()
            .DefineContainerInstance(containerGroupName + "-1")
                .WithImage(containerImage)
                .WithExternalTcpPort(80)
                .WithCpuCoreCount(1.0)
                .WithMemorySizeInGB(1)
                .Attach()
            .WithDnsPrefix(containerGroupName)
            .CreateAsync()
    );

    // Poll for the container group
    IContainerGroup containerGroup = null;
    while(containerGroup == null)
    {
        containerGroup = azure.ContainerGroups.GetByResourceGroup(resourceGroupName, containerGroupName);

        Console.Write(".");

        SdkContext.DelayProvider.Delay(1000);
    }

    Console.WriteLine();

    // Poll until the container group is running
    while(containerGroup.State != "Running")
    {
        Console.WriteLine($"Container group state: {containerGroup.Refresh().State}");
        
        Thread.Sleep(1000);
    }

    Console.WriteLine($"\nOnce DNS has propagated, container group '{containerGroup.Name}' will be reachable at http://{containerGroup.Fqdn}");
}

创建基于任务的容器组Create task-based container group

此示例创建包含单个基于任务的容器的容器组。This example creates a container group with a single task-based container. 该容器配置有重新启动策略“Never”以及一个自定义命令行The container is configured with a restart policy of "Never" and a custom command line.

如果要运行带有多个命令行参数的单个命令,例如 echo FOO BAR,必须以字符串数组的形式向 WithStartingCommandLines 方法提供这些参数。If you want to run a single command with several command-line arguments, for example echo FOO BAR, you must supply them as a string array to the WithStartingCommandLines method. 例如:For example:

WithStartingCommandLines("echo", "FOO", "BAR")

但是,如果要运行带有(可能)多个参数的多个命令,必须执行 shell,并将链接的命令作为参数传递。If, however, you want to run multiple commands with (potentially) multiple arguments, you must execute a shell and pass the chained commands as an argument. 例如,这样可以执行 echotail 命令:For example, this executes both an echo and a tail command:

WithStartingCommandLines("/bin/sh", "-c", "echo FOO BAR && tail -f /dev/null")

/// <summary>
/// Creates a container group with a single task-based container who's
/// restart policy is 'Never'. If specified, the container runs a custom
/// command line at startup.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group in which to create the container group.</param>
/// <param name="containerGroupName">The name of the container group to create.</param>
/// <param name="containerImage">The container image name and tag, for example 'microsoft\aci-wordcount:latest'.</param>
/// <param name="startCommandLine">The command line that should be executed when the container starts. This value can be <c>null</c>.</param>
private static void RunTaskBasedContainer(IAzure azure,
                                         string resourceGroupName, 
                                         string containerGroupName, 
                                         string containerImage,
                                         string startCommandLine)
{
    // If a start command wasn't specified, use a default
    if (String.IsNullOrEmpty(startCommandLine))
    {
        startCommandLine = "python wordcount.py http://shakespeare.mit.edu/romeo_juliet/full.html";
    }

    // Configure some environment variables in the container which the
    // wordcount.py or other script can read to modify its behavior.
    Dictionary<string, string> envVars = new Dictionary<string, string>
    {
        { "NumWords", "5" },
        { "MinLength", "8" }
    };

    Console.WriteLine($"\nCreating container group '{containerGroupName}' with start command '{startCommandLine}'");

    // Get the resource group's region
    IResourceGroup resGroup = azure.ResourceGroups.GetByName(resourceGroupName);
    Region azureRegion = resGroup.Region;

    // Create the container group
    var containerGroup = azure.ContainerGroups.Define(containerGroupName)
        .WithRegion(azureRegion)
        .WithExistingResourceGroup(resourceGroupName)
        .WithLinux()
        .WithPublicImageRegistryOnly()
        .WithoutVolume()
        .DefineContainerInstance(containerGroupName + "-1")
            .WithImage(containerImage)
            .WithExternalTcpPort(80)
            .WithCpuCoreCount(1.0)
            .WithMemorySizeInGB(1)
            .WithStartingCommandLines(startCommandLine.Split())
            .WithEnvironmentVariables(envVars)
            .Attach()
        .WithDnsPrefix(containerGroupName)
        .WithRestartPolicy(ContainerGroupRestartPolicy.Never)
        .Create();

    // Print the container's logs
    Console.WriteLine($"Logs for container '{containerGroupName}-1':");
    Console.WriteLine(containerGroup.GetLogContent(containerGroupName + "-1"));
}

列出容器组List container groups

此示例列出了资源组中的容器组。This example lists the container groups in a resource group.

/// <summary>
/// Prints the container groups in the specified resource group.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group containing the container group(s).</param>
private static void ListContainerGroups(IAzure azure, string resourceGroupName)
{
    Console.WriteLine($"Listing container groups in resource group '{resourceGroupName}'...");

    foreach (var containerGroup in azure.ContainerGroups.ListByResourceGroup(resourceGroupName))
    {
        Console.WriteLine($"{containerGroup.Name}");
    }
}

获取现有的容器组Get an existing container group

此示例获取驻留在资源组中的特定容器组,然后打印其一些属性及属性值。This example gets a specific container group residing in a resource group and then prints a few of its properties and their values.

/// <summary>
/// Gets the specified container group and then prints a few of its properties and their values.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group containing the container group.</param>
/// <param name="containerGroupName">The name of the container group whose details should be printed.</param>
private static void PrintContainerGroupDetails(IAzure azure, string resourceGroupName, string containerGroupName)
{
    Console.Write($"\nGetting container group details for container group '{containerGroupName}'...");

    IContainerGroup containerGroup = null;
    while (containerGroup == null)
    {
        Console.Write(".");

        containerGroup = azure.ContainerGroups.GetByResourceGroup(resourceGroupName, containerGroupName);

        SdkContext.DelayProvider.Delay(1000);
    }

    Console.WriteLine();
    Console.WriteLine(containerGroup.Name);
    Console.WriteLine("--------------------------------");
    Console.WriteLine($"State:  {containerGroup.State}");
    Console.WriteLine($"FQDN:   {containerGroup.Fqdn}");
    Console.WriteLine($"IP:     {containerGroup.IPAddress}");
    Console.WriteLine($"Region: {containerGroup.RegionName}");
}

删除容器组Delete a container group

此示例将从资源组中删除容器组。This example deletes a container group from a resource group.

/// <summary>
/// Deletes the specified container group.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group containing the container group.</param>
/// <param name="containerGroupName">The name of the container group to delete.</param>
private static void DeleteContainerGroup(IAzure azure, string resourceGroupName, string containerGroupName)
{
    IContainerGroup containerGroup = null;

    while (containerGroup == null)
    {
        containerGroup = azure.ContainerGroups.GetByResourceGroup(resourceGroupName, containerGroupName);

        SdkContext.DelayProvider.Delay(1000);
    }

    Console.WriteLine($"Deleting container group '{containerGroupName}'...");

    azure.ContainerGroups.DeleteById(containerGroup.Id);
}

API 参考API reference

示例Samples

详细了解可在应用中使用的示例 .NET 代码Explore more sample .NET code you can use in your apps.