You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python在Azure指定Vnet中创建包含单个实例的容器组

用Python创建集成指定VNet的Azure容器组操作指南

前置依赖

  • 已安装对应Azure Python SDK:pip install azure-mgmt-containerinstance azure-identity
  • 目标子网已完成委托配置,仅允许Microsoft.ContainerInstance/containerGroups资源部署,无其他业务资源占用
  • 已提前获取Azure订阅ID、资源组名称、目标VNet名称、目标子网名称等基础参数

完整实现代码

from azure.identity import DefaultAzureCredential
from azure.mgmt.containerinstance import ContainerInstanceManagementClient
from azure.mgmt.containerinstance.models import (
    ContainerGroup, Container, ResourceRequests, ResourceRequirements,
    ContainerPort, IpAddress, Port, OperatingSystemTypes,
    VnetConfiguration
)

# 下方参数替换为实际业务值
SUBSCRIPTION_ID = "你的Azure订阅ID"
RESOURCE_GROUP_NAME = "目标资源组名称"
CONTAINER_GROUP_NAME = "自定义容器组名称"
LOCATION = "部署区域,例如chinanorth3"
VNET_NAME = "指定VNet名称"
SUBNET_NAME = "已委托的目标子网名称"
CONTAINER_IMAGE = "待部署的容器镜像地址,例如mcr.microsoft.com/azure-app-service/samples/aspnetcore-hello-world:latest"
CONTAINER_CPU = 1
CONTAINER_MEMORY = 1.5
EXPOSED_PORT = 80

# 初始化ACI管理客户端
credential = DefaultAzureCredential()
aci_client = ContainerInstanceManagementClient(credential, SUBSCRIPTION_ID)

# 定义容器配置
container = Container(
    name=CONTAINER_GROUP_NAME,
    image=CONTAINER_IMAGE,
    resources=ResourceRequirements(
        requests=ResourceRequests(
            cpu=CONTAINER_CPU,
            memory_in_gb=CONTAINER_MEMORY
        )
    ),
    ports=[ContainerPort(port=EXPOSED_PORT)]
)

# 定义VNet集成配置
vnet_config = VnetConfiguration(
    vnet_id=f"/subscriptions/{SUBSCRIPTION_ID}/resourceGroups/{RESOURCE_GROUP_NAME}/providers/Microsoft.Network/virtualNetworks/{VNET_NAME}",
    subnet_id=f"/subscriptions/{SUBSCRIPTION_ID}/resourceGroups/{RESOURCE_GROUP_NAME}/providers/Microsoft.Network/virtualNetworks/{VNET_NAME}/subnets/{SUBNET_NAME}"
)

# 定义容器组全量配置
container_group = ContainerGroup(
    location=LOCATION,
    os_type=OperatingSystemTypes.linux,
    containers=[container],
    vnet_configuration=vnet_config,
    ip_address=IpAddress(
        type="Private",
        ports=[Port(protocol="Tcp", port=EXPOSED_PORT)]
    )
)

# 提交创建请求并等待完成
poller = aci_client.container_groups.begin_create_or_update(
    resource_group_name=RESOURCE_GROUP_NAME,
    container_group_name=CONTAINER_GROUP_NAME,
    container_group=container_group
)
result = poller.result()
print(f"部署完成,容器组私有IP为:{result.ip_address.ip}")

关键注意事项

  • 承载ACI的子网不能存在任何其他类型的资源,子网掩码建议至少为/24,满足ACI底层IP分配要求
  • 若子网未完成委托,可通过Azure CLI执行命令配置:az network vnet subnet update --name <子网名> --resource-group <资源组名> --vnet-name <VNet名> --delegations Microsoft.ContainerInstance/containerGroups
  • 如需部署Windows容器,将OperatingSystemTypes.linux替换为OperatingSystemTypes.windows即可

内容的提问来源于stack exchange,提问作者Hkni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 12:36:02