你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
快速入门:使用 Azure 容器注册表客户端库
参考本文开始使用 Azure 容器注册表客户端库。 按照以下步骤,尝试使用示例代码,对映像和项目执行数据平面操作。
使用 Azure 容器注册表客户端库执行以下操作:
- 列出注册表中的映像或项目
- 获取映像和项目、存储库以及标记的元数据
- 设置注册表项的读取/写入/删除属性
- 删除映像和项目、存储库和标记
Azure 容器注册表还有一个管理库,用于控制平面操作(包括创建和更新注册表)。
先决条件
若要使用此库,需要具有一个 Azure 订阅和一个 Azure 容器注册表。
若要创建新的 Azure 容器注册表,可使用 Azure 门户、Azure PowerShell 或 Azure CLI。 下面是使用 Azure CLI 的示例:
az acr create --name MyContainerRegistry --resource-group MyResourceGroup \ --location westus --sku Basic
将一个或多个容器映像推送到注册表。 有关具体步骤,请参阅使用 Docker CLI 将第一个映像推送到 Azure 容器注册表。
关键概念
- Azure 容器注册表可存储容器映像和 OCI 项目。
- 映像或项目由清单和各层组成 。
- 清单描述组成映像或项目的各个层。 它由其摘要进行唯一标识。
- 还可以对映像或项目进行标记,为其提供一个可读的别名。 映像或项目可以有零个或多个与之关联的标记,并且每个标记用于唯一标识该映像。
- 名称相同但具有不同标记的映像或项目的集合称为存储库。
有关详细信息,请参阅关于注册表、存储库和项目。
入门
若要开发可连接到 Azure 容器注册表实例的 .NET 应用程序代码,则需要 Azure.Containers.ContainerRegistry
库。
安装包
使用 NuGet 安装适用于 .NET 的 Azure 容器注册表客户端库:
dotnet add package Azure.Containers.ContainerRegistry --prerelease
验证客户端
若要使应用程序连接到注册表,需要创建一个可向其进行身份验证的 ContainerRegistryClient
。 使用 Azure 标识库来添加 Microsoft Entra ID 支持,以便向相应的 Azure 服务验证 Azure SDK 客户端。
在本地开发并调试应用程序时,可以使用自己的用户向注册表进行身份验证。 实现此目的的一种方式是向 Azure CLI 验证你的用户,并从该环境运行应用程序。 如果应用程序使用的客户端已构造为向 DefaultAzureCredential
进行身份验证,则它将正确地向指定终结点上的注册表进行身份验证。
// Create a ContainerRegistryClient that will authenticate to your registry through Azure Active Directory
Uri endpoint = new Uri("https://myregistry.azurecr.io");
ContainerRegistryClient client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential(),
new ContainerRegistryClientOptions()
{
Audience = ContainerRegistryAudience.AzureResourceManagerPublicCloud
});
有关更多在本地和部署环境中向 DefaultAzureCredential
进行身份验证的方法,请参阅 Azure 标识自述文件。 若要连接到非公共 Azure 云中的注册表,请参阅 API 参考。
若要详细了解如何将 Microsoft Entra ID 与 Azure 容器注册表结合使用,请参阅身份验证概述。
示例
每个示例均假设有一个 REGISTRY_ENDPOINT
环境变量,该变量设置为包含 https://
前缀和登录服务器名称的字符串,如“https://myregistry.azurecr.io"”。
以下示例使用返回任务的异步 API。 同步 API 也可用。
异步列出存储库
循环访问注册表中的存储库集合。
// Get the service endpoint from the environment
Uri endpoint = new Uri(Environment.GetEnvironmentVariable("REGISTRY_ENDPOINT"));
// Create a new ContainerRegistryClient
ContainerRegistryClient client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential(),
new ContainerRegistryClientOptions()
{
Audience = ContainerRegistryAudience.AzureResourceManagerPublicCloud
});
// Get the collection of repository names from the registry
AsyncPageable<string> repositories = client.GetRepositoryNamesAsync();
await foreach (string repository in repositories)
{
Console.WriteLine(repository);
}
异步设置项目属性
// Get the service endpoint from the environment
Uri endpoint = new Uri(Environment.GetEnvironmentVariable("REGISTRY_ENDPOINT"));
// Create a new ContainerRegistryClient
ContainerRegistryClient client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential(),
new ContainerRegistryClientOptions()
{
Audience = ContainerRegistryAudience.AzureResourceManagerPublicCloud
});
// Get the collection of repository names from the registry
AsyncPageable<string> repositories = client.GetRepositoryNamesAsync();
await foreach (string repository in repositories)
{
Console.WriteLine(repository);
}
异步删除映像
using System.Linq;
using Azure.Containers.ContainerRegistry;
using Azure.Identity;
// Get the service endpoint from the environment
Uri endpoint = new Uri(Environment.GetEnvironmentVariable("REGISTRY_ENDPOINT"));
// Create a new ContainerRegistryClient
ContainerRegistryClient client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential(),
new ContainerRegistryClientOptions()
{
Audience = ContainerRegistryAudience.AzureResourceManagerPublicCloud
});
// Iterate through repositories
AsyncPageable<string> repositoryNames = client.GetRepositoryNamesAsync();
await foreach (string repositoryName in repositoryNames)
{
ContainerRepository repository = client.GetRepository(repositoryName);
// Obtain the images ordered from newest to oldest
AsyncPageable<ArtifactManifestProperties> imageManifests =
repository.GetManifestPropertiesCollectionAsync(orderBy: ArtifactManifestOrderBy.LastUpdatedOnDescending);
// Delete images older than the first three.
await foreach (ArtifactManifestProperties imageManifest in imageManifests.Skip(3))
{
RegistryArtifact image = repository.GetArtifact(imageManifest.Digest);
Console.WriteLine($"Deleting image with digest {imageManifest.Digest}.");
Console.WriteLine($" Deleting the following tags from the image: ");
foreach (var tagName in imageManifest.Tags)
{
Console.WriteLine($" {imageManifest.RepositoryName}:{tagName}");
await image.DeleteTagAsync(tagName);
}
await image.DeleteAsync();
}
}
入门
目前支持的环境
- Java 开发工具包 (JDK) 8 版或更高版本。
添加包
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-containers-containerregistry</artifactId>
<version>1.0.0-beta.3</version>
</dependency>
验证客户端
Azure 标识库提供对身份验证的 Microsoft Entra ID 支持。
以下示例假设你有一个注册表终结点字符串,该字符串包含 https://
前缀和登录服务器的名称,如“https://myregistry.azurecr.io"”。
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
ContainerRegistryClient client = new ContainerRegistryClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildClient();
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
ContainerRegistryAsyncClient client = new ContainerRegistryClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildAsyncClient();
若要详细了解如何将 Microsoft Entra ID 与 Azure 容器注册表结合使用,请参阅身份验证概述。
示例
每个示例均假设有一个注册表终结点字符串,该字符串包含 https://
前缀和登录服务器的名称,如“https://myregistry.azurecr.io"”。
列出存储库名称
循环访问注册表中的存储库集合。
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
ContainerRegistryClient client = new ContainerRegistryClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildClient();
client.listRepositoryNames().forEach(repository -> System.out.println(repository));
编辑项目属性
TokenCredential defaultCredential = new DefaultAzureCredentialBuilder().build();
ContainerRegistryClient client = new ContainerRegistryClientBuilder()
.endpoint(endpoint)
.credential(defaultCredential)
.buildClient();
RegistryArtifact image = client.getArtifact(repositoryName, digest);
image.updateTagProperties(
tag,
new ArtifactTagProperties()
.setWriteEnabled(false)
.setDeleteEnabled(false));
删除映像
TokenCredential defaultCredential = new DefaultAzureCredentialBuilder().build();
ContainerRegistryClient client = new ContainerRegistryClientBuilder()
.endpoint(endpoint)
.credential(defaultCredential)
.buildClient();
final int imagesCountToKeep = 3;
for (String repositoryName : client.listRepositoryNames()) {
final ContainerRepository repository = client.getRepository(repositoryName);
// Obtain the images ordered from newest to oldest
PagedIterable<ArtifactManifestProperties> imageManifests =
repository.listManifestProperties(
ArtifactManifestOrderBy.LAST_UPDATED_ON_DESCENDING,
Context.NONE);
imageManifests.stream().skip(imagesCountToKeep)
.forEach(imageManifest -> {
System.out.printf(String.format("Deleting image with digest %s.%n", imageManifest.getDigest()));
System.out.printf(" This image has the following tags: ");
for (String tagName : imageManifest.getTags()) {
System.out.printf(" %s:%s", imageManifest.getRepositoryName(), tagName);
}
repository.getArtifact(imageManifest.getDigest()).delete();
});
}
入门
目前支持的环境
有关更多详细信息,请参阅我们的支持政策。
安装 @azure/container-registry
包
使用 npm
安装适用于 JavaScript 的容器注册表客户端库:
npm install @azure/container-registry
验证客户端
Azure 标识库提供对身份验证的 Microsoft Entra ID 支持。
const { ContainerRegistryClient } = require("@azure/container-registry");
const { DefaultAzureCredential } = require("@azure/identity");
const endpoint = process.env.CONTAINER_REGISTRY_ENDPOINT;
// Create a ContainerRegistryClient that will authenticate through Active Directory
const client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential());
若要详细了解如何将 Microsoft Entra ID 与 Azure 容器注册表结合使用,请参阅身份验证概述。
示例
每个示例均假设有一个 CONTAINER_REGISTRY_ENDPOINT
环境变量,该变量设置为包含 https://
前缀和登录服务器名称的字符串,如“https://myregistry.azurecr.io"”。
异步列出存储库
循环访问注册表中的存储库集合。
const { ContainerRegistryClient } = require("@azure/container-registry");
const { DefaultAzureCredential } = require("@azure/identity");
async function main() {
// endpoint should be in the form of "https://myregistryname.azurecr.io"
// where "myregistryname" is the actual name of your registry
const endpoint = process.env.CONTAINER_REGISTRY_ENDPOINT || "<endpoint>";
const client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential());
console.log("Listing repositories");
const iterator = client.listRepositoryNames();
for await (const repository of iterator) {
console.log(` repository: ${repository}`);
}
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
异步设置项目属性
const { ContainerRegistryClient } = require("@azure/container-registry");
const { DefaultAzureCredential } = require("@azure/identity");
async function main() {
// Get the service endpoint from the environment
const endpoint = process.env.CONTAINER_REGISTRY_ENDPOINT || "<endpoint>";
// Create a new ContainerRegistryClient and RegistryArtifact to access image operations
const client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential());
const image = client.getArtifact("library/hello-world", "v1");
// Set permissions on the image's "latest" tag
await image.updateTagProperties("latest", { canWrite: false, canDelete: false });
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
异步删除映像
const { ContainerRegistryClient } = require("@azure/container-registry");
const { DefaultAzureCredential } = require("@azure/identity");
async function main() {
// Get the service endpoint from the environment
const endpoint = process.env.CONTAINER_REGISTRY_ENDPOINT || "<endpoint>";
// Create a new ContainerRegistryClient
const client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential());
// Iterate through repositories
const repositoryNames = client.listRepositoryNames();
for await (const repositoryName of repositoryNames) {
const repository = client.getRepository(repositoryName);
// Obtain the images ordered from newest to oldest by passing the `orderBy` option
const imageManifests = repository.listManifestProperties({
orderBy: "LastUpdatedOnDescending"
});
const imagesToKeep = 3;
let imageCount = 0;
// Delete images older than the first three.
for await (const manifest of imageManifests) {
imageCount++;
if (imageCount > imagesToKeep) {
const image = repository.getArtifact(manifest.digest);
console.log(`Deleting image with digest ${manifest.digest}`);
console.log(` Deleting the following tags from the image:`);
for (const tagName of manifest.tags) {
console.log(` ${manifest.repositoryName}:${tagName}`);
image.deleteTag(tagName);
}
await image.delete();
}
}
}
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
入门
安装包
使用 pip 安装适用于 Python 的 Azure 容器注册表客户端库:
pip install --pre azure-containerregistry
对客户端进行身份验证
Azure 标识库提供对身份验证的 Microsoft Entra ID 支持。 DefaultAzureCredential
假设已设置 AZURE_CLIENT_ID
、AZURE_TENANT_ID
和 AZURE_CLIENT_SECRET
环境变量。 有关详细信息,请参阅 Azure 标识环境变量。
# Create a ContainerRegistryClient that will authenticate through Active Directory
from azure.containerregistry import ContainerRegistryClient
from azure.identity import DefaultAzureCredential
account_url = "https://mycontainerregistry.azurecr.io"
client = ContainerRegistryClient(account_url, DefaultAzureCredential())
示例
每个示例均假设有一个 CONTAINERREGISTRY_ENDPOINT
环境变量,该变量设置为包含 https://
前缀和登录服务器名称的字符串,如“https://myregistry.azurecr.io"”。
异步列出标记
此示例假设注册表具有存储库 hello-world
。
import asyncio
from dotenv import find_dotenv, load_dotenv
import os
from azure.containerregistry.aio import ContainerRegistryClient
from azure.identity.aio import DefaultAzureCredential
class ListTagsAsync(object):
def __init__(self):
load_dotenv(find_dotenv())
async def list_tags(self):
# Create a new ContainerRegistryClient
audience = "https://management.azure.com"
account_url = os.environ["CONTAINERREGISTRY_ENDPOINT"]
credential = DefaultAzureCredential()
client = ContainerRegistryClient(account_url, credential, audience=audience)
manifest = await client.get_manifest_properties("library/hello-world", "latest")
print(manifest.repository_name + ": ")
for tag in manifest.tags:
print(tag + "\n")
异步设置项目属性
此示例假设注册表具有存储库 hello-world
,其中映像标记为 v1
。
import asyncio
from dotenv import find_dotenv, load_dotenv
import os
from azure.containerregistry.aio import ContainerRegistryClient
from azure.identity.aio import DefaultAzureCredential
class SetImagePropertiesAsync(object):
def __init__(self):
load_dotenv(find_dotenv())
async def set_image_properties(self):
# Create a new ContainerRegistryClient
account_url = os.environ["CONTAINERREGISTRY_ENDPOINT"]
audience = "https://management.azure.com"
credential = DefaultAzureCredential()
client = ContainerRegistryClient(account_url, credential, audience=audience)
# [START update_manifest_properties]
# Set permissions on the v1 image's "latest" tag
await client.update_manifest_properties(
"library/hello-world",
"latest",
can_write=False,
can_delete=False
)
# [END update_manifest_properties]
# After this update, if someone were to push an update to "myacr.azurecr.io\hello-world:v1", it would fail.
# It's worth noting that if this image also had another tag, such as "latest", and that tag did not have
# permissions set to prevent reads or deletes, the image could still be overwritten. For example,
# if someone were to push an update to "myacr.azurecr.io\hello-world:latest"
# (which references the same image), it would succeed.
异步删除映像
import asyncio
from dotenv import find_dotenv, load_dotenv
import os
from azure.containerregistry import ManifestOrder
from azure.containerregistry.aio import ContainerRegistryClient
from azure.identity.aio import DefaultAzureCredential
class DeleteImagesAsync(object):
def __init__(self):
load_dotenv(find_dotenv())
async def delete_images(self):
# [START list_repository_names]
audience = "https://management.azure.com"
account_url = os.environ["CONTAINERREGISTRY_ENDPOINT"]
credential = DefaultAzureCredential()
client = ContainerRegistryClient(account_url, credential, audience=audience)
async with client:
async for repository in client.list_repository_names():
print(repository)
# [END list_repository_names]
# [START list_manifest_properties]
# Keep the three most recent images, delete everything else
manifest_count = 0
async for manifest in client.list_manifest_properties(repository, order_by=ManifestOrder.LAST_UPDATE_TIME_DESCENDING):
manifest_count += 1
if manifest_count > 3:
await client.delete_manifest(repository, manifest.digest)
# [END list_manifest_properties]
入门
源代码 | 包 (pkg.go.dev) | REST API 引用
安装包
使用 go get
安装适用于 Go 的 Azure 容器注册表客户端库:
go get github.com/Azure/azure-sdk-for-go/sdk/containers/azcontainerregistry
验证客户端
在本地开发和调试应用程序时,可以使用 azidentity.NewDefaultAzureCredential 进行身份验证。 建议在生产环境中使用托管标识。
import (
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/containers/azcontainerregistry"
"log"
)
func main() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
client, err := azcontainerregistry.NewClient("https://myregistry.azurecr.io", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
}
有关其他身份验证方法的更多信息,请参阅 azidentity 文档。
示例
每个示例都假定容器注册表终结点 URL 为“https://myregistry.azurecr.io";。
列出标记
此示例假设注册表具有存储库 hello-world
。
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/containers/azcontainerregistry"
"log"
)
func Example_listTagsWithAnonymousAccess() {
client, err := azcontainerregistry.NewClient("https://myregistry.azurecr.io", nil, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
ctx := context.Background()
pager := client.NewListTagsPager("library/hello-world", nil)
for pager.More() {
page, err := pager.NextPage(ctx)
if err != nil {
log.Fatalf("failed to advance page: %v", err)
}
for _, v := range page.Tags {
fmt.Printf("tag: %s\n", *v.Name)
}
}
}
编辑项目属性
此示例假设注册表具有存储库 hello-world
,其中映像标记为 latest
。
package azcontainerregistry_test
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/containers/azcontainerregistry"
"log"
)
func Example_setArtifactProperties() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
client, err := azcontainerregistry.NewClient("https://myregistry.azurecr.io", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
ctx := context.Background()
res, err := client.UpdateTagProperties(ctx, "library/hello-world", "latest", &azcontainerregistry.ClientUpdateTagPropertiesOptions{
Value: &azcontainerregistry.TagWriteableProperties{
CanWrite: to.Ptr(false),
CanDelete: to.Ptr(false),
}})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
fmt.Printf("repository library/hello-world - tag latest: 'CanWrite' property: %t, 'CanDelete' property: %t\n", *res.Tag.ChangeableAttributes.CanWrite, *res.Tag.ChangeableAttributes.CanDelete)
}
删除映像
package azcontainerregistry_test
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/containers/azcontainerregistry"
"log"
)
func Example_deleteImages() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
client, err := azcontainerregistry.NewClient("https://myregistry.azurecr.io", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
ctx := context.Background()
repositoryPager := client.NewListRepositoriesPager(nil)
for repositoryPager.More() {
repositoryPage, err := repositoryPager.NextPage(ctx)
if err != nil {
log.Fatalf("failed to advance repository page: %v", err)
}
for _, r := range repositoryPage.Repositories.Names {
manifestPager := client.NewListManifestsPager(*r, &azcontainerregistry.ClientListManifestsOptions{
OrderBy: to.Ptr(azcontainerregistry.ArtifactManifestOrderByLastUpdatedOnDescending),
})
for manifestPager.More() {
manifestPage, err := manifestPager.NextPage(ctx)
if err != nil {
log.Fatalf("failed to advance manifest page: %v", err)
}
imagesToKeep := 3
for i, m := range manifestPage.Manifests.Attributes {
if i >= imagesToKeep {
for _, t := range m.Tags {
fmt.Printf("delete tag from image: %s", *t)
_, err := client.DeleteTag(ctx, *r, *t, nil)
if err != nil {
log.Fatalf("failed to delete tag: %v", err)
}
}
_, err := client.DeleteManifest(ctx, *r, *m.Digest, nil)
if err != nil {
log.Fatalf("failed to delete manifest: %v", err)
}
fmt.Printf("delete image with digest: %s", *m.Digest)
}
}
}
}
}
}
清理资源
如果想要清理并删除 Azure 容器注册表,可以删除资源或资源组。 删除资源组同时也会删除与之相关联的任何其他资源。
后续步骤
在本快速入门中,你了解了如何使用 Azure 容器注册表客户端库来对容器注册表中的映像和项目执行各种操作。
有关详细信息,请参阅 API 参考文档:
了解 Azure容器注册表 REST API。