pustaka klien Azure Container Registry untuk JavaScript - versi 1.1.0
Azure Container Registry memungkinkan Anda menyimpan dan mengelola gambar kontainer dan artefak dalam registri privat untuk semua jenis penyebaran kontainer.
Gunakan pustaka klien untuk Azure Container Registry untuk:
- Membuat daftar citra atau artefak dalam registri
- Mendapatkan metadata untuk gambar dan artefak, repositori, dan tag
- Mengatur properti baca/tulis/hapus pada item registri
- Menghapus gambar dan artefak, repositori, dan tag
Tautan utama:
Memulai
Lingkungan yang didukung saat ini
Lihat kebijakan dukungan kami untuk detail selengkapnya.
Catatan: Paket ini tidak dapat digunakan di browser karena keterbatasan layanan, silakan lihat dokumen ini untuk panduan.
Prasyarat
Untuk membuat Container Registry baru, Anda dapat menggunakan Portal Microsoft Azure, Azure PowerShell, atau Azure CLI. Berikut adalah contoh menggunakan SDK:
az acr create --name MyContainerRegistry --resource-group MyResourceGroup --location westus --sku Basic
Pasang paket @azure/container-registry
Pasang pustaka klien Azure Container Registry untuk JavaScript dengan npm
:
npm install @azure/container-registry
Autentikasi klien
Pustaka Azure Identity menyediakan dukungan Azure Active Directory yang mudah untuk autentikasi.
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,
});
Perhatikan bahwa sampel ini mengasumsikan Anda memiliki CONTAINER_REGISTRY_ENDPOINT
set variabel lingkungan, yang merupakan URL termasuk nama server login dan awalan https://
.
National Clouds
Untuk mengautentikasi dengan registri di National Cloud, Anda harus membuat penambahan berikut ke konfigurasi Anda:
- Mengatur dalam
authorityHost
opsi kredensial atau melaluiAZURE_AUTHORITY_HOST
variabel lingkungan - Atur di
audience
ContainerRegistryClientOptions
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,
}
);
Untuk informasi selengkapnya tentang menggunakan AAD dengan Azure Container Registry, silakan lihat Gambaran Umum Autentikasi layanan.
Konsep utama
Registri menyimpan gambar Docker dan Artefak OCI. Citra atau artefak terdiri dari manifes dan lapisan. Manifes gambar menjelaskan lapisan yang membentuk gambar, dan diidentifikasi secara unik oleh hashnya. Gambar juga dapat "ditandai" untuk memberinya alias yang dapat dibaca manusia. Gambar atau artefak dapat memiliki nol atau lebih tag yang terkait dengannya, dan setiap tag secara unik mengidentifikasi gambar. Kumpulan gambar yang memiliki nama yang sama tetapi memiliki tag yang berbeda, disebut sebagai repositori.
Untuk informasi selengkapnya, silakan lihat Konsep Container Registry.
Contoh
Operasi registri
Mencantumkan repositori
Lakukan iterasi melalui kumpulan repositori dalam registri.
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);
});
Mencantumkan tag dengan akses anonim
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);
});
Mengatur properti artefak
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);
});
Hapus gambar
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);
});
Operasi blob dan manifes
Unggah gambar
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);
});
Mengunduh gambar
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);
});
Hapus manifes
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);
});
Menghapus 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);
}
}
Pemecahan Masalah
Untuk informasi tentang pemecahan masalah, lihat panduan pemecahan masalah.
Langkah berikutnya
Silakan lihat direktori sampel untuk contoh terperinci yang menunjukkan cara menggunakan pustaka klien.
Berkontribusi
Jika Anda ingin berkontribusi pada pustaka ini, baca panduan berkontribusi untuk mempelajari selengkapnya tentang cara membuat dan menguji kode.
Proyek terkait
Azure SDK for JavaScript
Saran dan Komentar
https://aka.ms/ContentUserFeedback.
Segera hadir: Sepanjang tahun 2024 kami akan menghentikan penggunaan GitHub Issues sebagai mekanisme umpan balik untuk konten dan menggantinya dengan sistem umpan balik baru. Untuk mengetahui informasi selengkapnya, lihat:Kirim dan lihat umpan balik untuk