JavaScript용 Azure Container Registry 클라이언트 라이브러리 - 버전 1.1.0

Azure Container Registry 모든 유형의 컨테이너 배포에 대해 프라이빗 레지스트리에 컨테이너 이미지 및 아티팩트 저장 및 관리할 수 있습니다.

Azure Container Registry 클라이언트 라이브러리를 사용하여 다음을 수행합니다.

  • 레지스트리의 이미지 또는 아티팩트 나열
  • 이미지 및 아티팩트, 리포지토리 및 태그에 대한 메타데이터 가져오기
  • 레지스트리 항목에 대한 읽기/쓰기/삭제 속성 설정
  • 이미지 및 아티팩트, 리포지토리 및 태그 삭제

주요 링크:

시작

현재 지원되는 환경

자세한 내용은 지원 정책을 참조하세요.

참고: 서비스 제한으로 인해 브라우저에서 이 패키지를 사용할 수 없습니다. 지침 은 이 문서를 참조하세요.

필수 구성 요소

새 Container Registry를 만들려면 Azure Portal, Azure PowerShell 또는 Azure CLI를 사용할 수 있습니다. 다음은 Azure CLI 사용 예입니다.

az acr create --name MyContainerRegistry --resource-group MyResourceGroup --location westus --sku Basic

@azure/container-registry 패키지를 설치합니다.

npm을 사용하여 JavaScript용 Container Registry 클라이언트 라이브러리를 설치합니다.

npm install @azure/container-registry

클라이언트 인증

Azure ID 라이브러리는 인증을 위한 간편한 Azure Active Directory 지원을 제공합니다.

const {
  ContainerRegistryClient,
  KnownContainerRegistryAudience,
} = 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(), {
  audience: KnownContainerRegistryAudience.AzureResourceManagerPublicCloud,
});

이러한 샘플에서는 CONTAINER_REGISTRY_ENDPOINT 로그인 서버의 이름 및 접두사를 포함하는 URL인 환경 변수 집합이 https:// 있다고 가정합니다.

국가별 클라우드

내셔널 클라우드에서 레지스트리를 사용하여 인증하려면 구성에 다음을 추가해야 합니다.

  • authorityHost 자격 증명 옵션에서 또는 환경 변수를 통해 을 AZURE_AUTHORITY_HOST 설정합니다.
  • 에서 설정 audienceContainerRegistryClientOptions
const {
  ContainerRegistryClient,
  KnownContainerRegistryAudience,
} = require("@azure/container-registry");
const { DefaultAzureCredential, AzureAuthorityHosts } = require("@azure/identity");

const endpoint = process.env.CONTAINER_REGISTRY_ENDPOINT;
// Create a ContainerRegistryClient that will authenticate through AAD in the China national cloud
const client = new ContainerRegistryClient(
  endpoint,
  new DefaultAzureCredential({ authorityHost: AzureAuthorityHosts.AzureChina }),
  {
    audience: KnownContainerRegistryAudience.AzureResourceManagerChina,
  }
);

Azure Container Registry AAD를 사용하는 방법에 대한 자세한 내용은 서비스의 인증 개요를 참조하세요.

주요 개념

레지스트리에는 Docker 이미지 및 OCI 아티팩트가 저장됩니다. 이미지 또는 아티팩트는 매니페스트레이어로 구성됩니다. 이미지의 매니페스트는 이미지를 구성하는 레이어를 설명하고 다이 스트를 통해 고유하게 식별됩니다. 이미지를 "태그"로 지정하여 사람이 읽을 수 있는 별칭을 제공할 수도 있습니다. 이미지 또는 아티팩트와 연결된 태그가 0개 이상 있을 수 있으며 각 태그는 이미지를 고유하게 식별합니다. 이름이 같지만 태그가 다른 이미지 컬렉션을 리포지토리라고 합니다.

자세한 내용은 Container Registry 개념을 참조하세요.

예제

레지스트리 작업

리포지토리 나열

레지스트리의 리포지토리 컬렉션을 반복합니다.

const {
  ContainerRegistryClient,
  KnownContainerRegistryAudience,
} = 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(), {
    audience: KnownContainerRegistryAudience.AzureResourceManagerPublicCloud,
  });

  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,
  KnownContainerRegistryAudience,
} = require("@azure/container-registry");

async function main() {
  // Get the service endpoint from the environment
  const endpoint = process.env.CONTAINER_REGISTRY_ENDPOINT || "<endpoint>";

  // Create a new ContainerRegistryClient for anonymous access
  const client = new ContainerRegistryClient(endpoint, {
    audience: KnownContainerRegistryAudience.AzureResourceManagerPublicCloud,
  });

  // Obtain a RegistryArtifact object to get access to image operations
  const image = client.getArtifact("library/hello-world", "latest");

  // List the set of tags on the hello_world image tagged as "latest"
  const tagIterator = image.listTagProperties();

  // Iterate through the image's tags, listing the tagged alias for the image
  console.log(`${image.fullyQualifiedReference}  has the following aliases:`);
  for await (const tag of tagIterator) {
    console.log(`  ${tag.registryLoginServer}/${tag.repositoryName}:${tag.name}`);
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

아티팩트 속성 설정

const {
  ContainerRegistryClient,
  KnownContainerRegistryAudience,
} = 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(), {
    audience: KnownContainerRegistryAudience.AzureResourceManagerPublicCloud,
  });
  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,
  KnownContainerRegistryAudience,
} = 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(), {
    audience: KnownContainerRegistryAudience.AzureResourceManagerPublicCloud,
  });

  // 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 `order` option
    const imageManifests = repository.listManifestProperties({
      order: "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);
});

Blob 및 매니페스트 작업

이미지 업로드

const { ContainerRegistryContentClient } = require("@azure/container-registry");
const { DefaultAzureCredential } = require("@azure/identity");
require("dotenv").config();

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 repository = process.env.CONTAINER_REGISTRY_REPOSITORY || "library/hello-world";
  const client = new ContainerRegistryContentClient(
    endpoint,
    repository,
    new DefaultAzureCredential()
  );

  const config = Buffer.from("Sample config");
  const { digest: configDigest, sizeInBytes: configSize } = await client.uploadBlob(config);

  const layer = Buffer.from("Sample layer");
  const { digest: layerDigest, sizeInBytes: layerSize } = await client.uploadBlob(layer);

  const manifest = {
    schemaVersion: 2,
    config: {
      digest: configDigest,
      size: configSize,
      mediaType: "application/vnd.oci.image.config.v1+json",
    },
    layers: [
      {
        digest: layerDigest,
        size: layerSize,
        mediaType: "application/vnd.oci.image.layer.v1.tar",
      },
    ],
  };

  await client.setManifest(manifest, { tag: "demo" });
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

이미지 다운로드

const {
  ContainerRegistryContentClient,
  KnownManifestMediaType,
} = require("@azure/container-registry");
const { DefaultAzureCredential } = require("@azure/identity");
const dotenv = require("dotenv");
const fs = require("fs");
dotenv.config();

function trimSha(digest) {
  const index = digest.indexOf(":");
  return index === -1 ? digest : digest.substring(index);
}

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 repository = process.env.CONTAINER_REGISTRY_REPOSITORY || "library/hello-world";
  const client = new ContainerRegistryContentClient(
    endpoint,
    repository,
    new DefaultAzureCredential()
  );

  // Download the manifest to obtain the list of files in the image based on the tag
  const result = await client.getManifest("demo");

  if (result.mediaType !== KnownManifestMediaType.OciImageManifest) {
    throw new Error("Expected an OCI image manifest");
  }

  const manifest = result.manifest;

  // Manifests of all media types have a buffer containing their content; this can be written to a file.
  fs.writeFileSync("manifest.json", result.content);

  const configResult = await client.downloadBlob(manifest.config.digest);
  const configFile = fs.createWriteStream("config.json");
  configResult.content.pipe(configFile);

  // Download and write out the layers
  for (const layer of manifest.layers) {
    const fileName = trimSha(layer.digest);
    const layerStream = fs.createWriteStream(fileName);
    const downloadLayerResult = await client.downloadBlob(layer.digest);
    downloadLayerResult.content.pipe(layerStream);
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

매니페스트 삭제

const { ContainerRegistryContentClient } = require("@azure/container-registry");
const { DefaultAzureCredential } = require("@azure/identity");
require("dotenv").config();

async function main() {
  // Get the service endpoint from the environment
  const endpoint = process.env.CONTAINER_REGISTRY_ENDPOINT || "<endpoint>";
  const repository = process.env.CONTAINER_REGISTRY_REPOSITORY || "library/hello-world";
  // Create a new ContainerRegistryClient
  const client = new ContainerRegistryContentClient(
    endpoint,
    repository,
    new DefaultAzureCredential()
  );

  const downloadResult = await client.getManifest("latest");
  await client.deleteManifest(downloadResult.digest);
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

Blob 삭제

const {
  ContainerRegistryContentClient,
  KnownManifestMediaType,
} = require("@azure/container-registry");
const { DefaultAzureCredential } = require("@azure/identity");
require("dotenv").config();

async function main() {
  // Get the service endpoint from the environment
  const endpoint = process.env.CONTAINER_REGISTRY_ENDPOINT || "<endpoint>";
  const repository = process.env.CONTAINER_REGISTRY_REPOSITORY || "library/hello-world";
  // Create a new ContainerRegistryClient
  const client = new ContainerRegistryContentClient(
    endpoint,
    repository,
    new DefaultAzureCredential()
  );

  const downloadResult = await client.getManifest("latest");

  if (downloadResult.mediaType !== KnownManifestMediaType.OciImageManifest) {
    throw new Error("Expected an OCI image manifest");
  }

  for (const layer of downloadResult.manifest.layers) {
    await client.deleteBlob(layer.digest);
  }
}

문제 해결

문제 해결에 대한 자세한 내용은 문제 해결 가이드를 참조하세요.

다음 단계

클라이언트 라이브러리를 사용하는 방법을 보여 주는 자세한 예제는 샘플 디렉터리를 참조하세요.

참여

이 라이브러리에 기여하려면 기여 가이드 를 참조하여 코드를 빌드하고 테스트하는 방법에 대해 자세히 알아보세요.

Impressions