基于ACR镜像创建Azure容器实例:通过AZ CLI添加密钥与卷配置
解决ACI中缺少密钥与配置文件的问题
一、先明确ACI与Docker Compose的差异
Docker Compose的secrets和本地volumes绑定在ACI中无法直接复用:
- 本地文件挂载(
./db.config)需要替换为Azure文件共享卷 - Docker Secrets需要替换为ACI秘密卷或Azure Key Vault集成方案
二、步骤1:配置密钥(对应db.secrets)
方式1:直接创建ACI秘密卷
将本地db.secrets内容转为ACI支持的格式后挂载:
把
db.secrets内容编码为base64:base64 -w 0 ./db.secrets复制输出的base64字符串备用。
创建ACI时通过参数定义并挂载秘密:
az container create \ --resource-group <你的资源组名> \ --name CreditAppACI \ --image xyz.azurecr.io/creditapp \ --ports 8080 8000 1433 \ --secrets "db-secret=<上面复制的base64字符串>" \ --secret-mounts "secret-name=db-secret,target-path=/opt/scr/secrets/db/db.secrets,mode=0400"
方式2:集成Azure Key Vault(更安全)
敏感密钥建议用Key Vault存储管理:
- 将
db.secrets存入Key Vault:az keyvault secret set \ --vault-name <你的Key Vault名称> \ --name db-secret \ --file ./db.secrets - 创建ACI并挂载Key Vault中的秘密(需先给ACI系统身份分配Key Vault的「秘密用户」角色):
az container create \ --resource-group <你的资源组名> \ --name CreditAppACI \ --image xyz.azurecr.io/creditapp \ --ports 8080 8000 1433 \ --assign-identity [system] \ --secrets "db-secret=https://<你的Key Vault名称>.vault.azure.net/secrets/db-secret" \ --secret-mounts "secret-name=db-secret,target-path=/opt/scr/secrets/db/db.secrets,mode=0400"
三、步骤2:配置配置文件卷(对应db.config)
ACI无法直接挂载本地文件,需借助Azure文件共享:
创建存储账户和文件共享:
# 创建存储账户 az storage account create \ --name <你的存储账户名> \ --resource-group <你的资源组名> \ --sku Standard_LRS \ --location <你的区域> # 获取存储账户密钥 STORAGE_KEY=$(az storage account keys list --resource-group <你的资源组名> --account-name <你的存储账户名> --query "[0].value" -o tsv) # 创建文件共享 az storage share create \ --name config-share \ --account-name <你的存储账户名> \ --account-key $STORAGE_KEY上传本地
db.config到文件共享:az storage file upload \ --share-name config-share \ --source ./db.config \ --path db.config \ --account-name <你的存储账户名> \ --account-key $STORAGE_KEY创建ACI时挂载该文件共享到目标路径:
az container create \ --resource-group <你的资源组名> \ --name CreditAppACI \ --image xyz.azurecr.io/creditapp \ --ports 8080 8000 1433 \ --azure-file-volume-account-name <你的存储账户名> \ --azure-file-volume-account-key $STORAGE_KEY \ --azure-file-volume-share-name config-share \ --azure-file-volume-mount-path /opt/scr/config/db/注:挂载路径为目录,上传的
db.config会自动出现在该目录下。
四、完整命令:同时挂载密钥和配置卷
整合上述步骤,用单命令完成ACI创建:
# 获取存储账户密钥 STORAGE_KEY=$(az storage account keys list --resource-group <你的资源组名> --account-name <你的存储账户名> --query "[0].value" -o tsv) # 转换db.secrets为base64编码 DB_SECRET_BASE64=$(base64 -w 0 ./db.secrets) # 创建ACI并挂载密钥与配置卷 az container create \ --resource-group <你的资源组名> \ --name CreditAppACI \ --image xyz.azurecr.io/creditapp \ --ports 8080 8000 1433 \ --secrets "db-secret=$DB_SECRET_BASE64" \ --secret-mounts "secret-name=db-secret,target-path=/opt/scr/secrets/db/db.secrets,mode=0400" \ --azure-file-volume-account-name <你的存储账户名> \ --azure-file-volume-account-key $STORAGE_KEY \ --azure-file-volume-share-name config-share \ --azure-file-volume-mount-path /opt/scr/config/db/
内容的提问来源于stack exchange,提问作者Ziggy
相关产品推荐
相关产品推荐

