配置文件存放 Docker 镜像列表
- docker-images.txt
说明:该示例文件格式(image-name:tag),配置需要下载的 docker 镜像信息。
nginx:latest
mongo:7.0.14
mongo-express:1.0.2-20-alpine3.19
# 这是一个注释
Shell 脚本下载 docker 镜像
- download_images.sh
#!/bin/bash
# 检查是否安装了 Docker
if ! command -v docker &> /dev/null
then
echo "Docker 未安装,请先安装 Docker。"
exit 1
fi
# 检查配置文件是否存在
CONFIG_FILE="docker-images.txt"
if [ ! -f "$CONFIG_FILE" ]; then
echo "配置文件 $CONFIG_FILE 不存在。"
exit 1
fi
# 读取配置文件并逐行处理
while IFS= read -r line
do
# 跳过空行和注释行(以 # 开头)
if [[ -z "$line" || "$line" =~ ^# ]]; then
continue
fi
# 提取镜像名称和标签
IMAGE_NAME=$(echo "$line" | cut -d':' -f1)
IMAGE_TAG=$(echo "$line" | cut -d':' -f2)
# 如果 IMAGE_TAG 为空,则默认为 latest
if [ -z "$IMAGE_TAG" ]; then
IMAGE_TAG="latest"
fi
# 下载 Docker 镜像
echo "正在下载 Docker 镜像: ${IMAGE_NAME}:${IMAGE_TAG}"
docker pull "${IMAGE_NAME}:${IMAGE_TAG}"
# 检查镜像是否下载成功
if [ $? -eq 0 ]; then
echo "Docker 镜像 ${IMAGE_NAME}:${IMAGE_TAG} 下载成功。"
else
echo "Docker 镜像 ${IMAGE_NAME}:${IMAGE_TAG} 下载失败。"
exit 1
fi
done < "$CONFIG_FILE"
使用方式
- 创建配置文件:
- 创建 docker-images.txt 文件并添加需要下载的镜像列表。
- 运行脚本:
# 赋予脚本执行权限
chmod +x download_images.sh
# 运行脚本
./download_images.sh
PowerShell 下载 docker 镜像
- download_images.ps1
# 检查是否安装了 Docker
if (-not (Get-Command docker -ErrorAction SilentlyContinue)) {
Write-Output "Docker 未安装,请先安装 Docker。"
exit 1
}
# 配置文件路径
$CONFIG_FILE = "docker-images.txt"
# 检查配置文件是否存在
if (-not (Test-Path $CONFIG_FILE)) {
Write-Output "配置文件 $CONFIG_FILE 不存在。"
exit 1
}
# 读取配置文件并逐行处理
Get-Content $CONFIG_FILE | ForEach-Object {
$line = $_.Trim()
# 跳过空行和注释行(以 # 开头)
if ([string]::IsNullOrEmpty($line) -or $line.StartsWith("#")) {
return
}
# 提取镜像名称和标签
$parts = $line -split ':'
$IMAGE_NAME = $parts[0]
$IMAGE_TAG = if ($parts.Length -gt 1) {
$parts[1] } else {
"latest" }
# 下载 Docker 镜像
Write-Output "正在下载 Docker 镜像: ${IMAGE_NAME}:${IMAGE_TAG}"
$result = docker pull "${IMAGE_NAME}:${IMAGE_TAG}"
# 检查镜像是否下载成功
if ($LASTEXITCODE -eq 0) {
Write-Output "Docker 镜像 ${IMAGE_NAME}:${IMAGE_TAG} 下载成功。"
} else {
Write-Output "Docker 镜像 ${IMAGE_NAME}:${IMAGE_TAG} 下载失败。"
exit 1
}
}
使用方式
2、运行脚本
2.1 保存上述 PowerShell 脚本为 download_images.ps1。
2.2 打开 PowerShell 并赋予脚本执行权限(如果需要):
powershell
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
2.3 运行脚本:
powershell
.\download_images.ps1
js 脚本下载 docker 镜像
- download_images.js
const fs = require('fs');
const {
exec } = require('child_process');
// 检查是否安装了 Docker
exec('docker --version', (error, stdout, stderr) => {
if (error) {
console.error("Docker 未安装,请先安装 Docker。");
process.exit(1);
}
console.log(stdout.trim());
// 配置文件路径
const CONFIG_FILE = 'docker-images.txt';
// 检查配置文件是否存在
if (!fs.existsSync(CONFIG_FILE)) {
console.error(`配置文件 ${
CONFIG_FILE} 不存在。`);
process.exit(1);
}
// 读取配置文件并逐行处理
fs.readFile(CONFIG_FILE, 'utf8', (err, data) => {
if (err) {
console.error(`读取配置文件 ${
CONFIG_FILE} 失败:`, err);
process.exit(1);
}
const lines = data.split('\n');
lines.forEach(line => {
const trimmedLine = line.trim();
// 跳过空行和注释行(以 # 开头)
if (trimmedLine === '' || trimmedLine.startsWith('#')) {
return;
}
// 提取镜像名称和标签
const parts = trimmedLine.split(':');
const IMAGE_NAME = parts[0];
const IMAGE_TAG = parts.length > 1 ? parts[1] : 'latest';
// 下载 Docker 镜像
console.log(`正在下载 Docker 镜像: ${
IMAGE_NAME}:${
IMAGE_TAG}`);
exec(`docker pull ${
IMAGE_NAME}:${
IMAGE_TAG}`, (error, stdout, stderr) => {
if (error) {
console.error(`Docker 镜像 ${
IMAGE_NAME}:${
IMAGE_TAG} 下载失败。`);
console.error(stderr);
process.exit(1);
}
console.log(`Docker 镜像 ${
IMAGE_NAME}:${
IMAGE_TAG} 下载成功。`);
console.log(stdout);
});
});
});
});
使用方式
2、保存 Node.js
脚本:
- 将上述脚本保存为
download_images.js
。
3、运行脚本:
打开终端或命令提示符,导航到保存脚本的目录。
运行脚本:
bash
node download_images.js
使用 C# 实现 docker 镜像下载
异步方式,批量下载 docker
镜像;
using System;
using System.IO;
using System.Diagnostics;
namespace ConsoleApp1;
class Program
{
static async Task Main(string[] args)
{
// 检查是否安装了 Docker
if (!await IsDockerInstalledAsync())
{
Console.WriteLine("Docker 未安装,请先安装 Docker。");
Environment.Exit(1);
}
// 配置文件路径
string config_file = "docker-images.txt";
// 检查配置文件是否存在
if (!File.Exists(config_file))
{
Console.WriteLine($"配置文件 {config_file} 不存在。");
Environment.Exit(1);
}
// 读取配置文件并逐行处理
string[] lines = File.ReadAllLines(config_file);
foreach (string line in lines)
{
string trimmedLine = line.Trim();
// 跳过空行和注释行(以 # 开头)
if (string.IsNullOrEmpty(trimmedLine) || trimmedLine.StartsWith("#"))
{
continue;
}
// 提取镜像名称和标签
string[] parts = trimmedLine.Split(':');
string image_name = parts[0];
string image_tag = parts.Length > 1 ? parts[1] : "latest";
// 下载 Docker 镜像
Console.WriteLine($"正在下载 Docker 镜像: {image_name}:{image_tag}");
if (await PullDockerImageAsync(image_name, image_tag))
{
Console.WriteLine($"Docker 镜像 {image_name}:{image_tag} 下载成功。");
}
else
{
Console.WriteLine($"Docker 镜像 {image_name}:{image_tag} 下载失败。");
Environment.Exit(1);
}
}
}
static async Task<bool> IsDockerInstalledAsync()
{
try
{
ProcessStartInfo psi = new()
{
FileName = "docker",
Arguments = "--version",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
using Process process = new() {
StartInfo = psi };
process.Start();
string output = await process.StandardOutput.ReadToEndAsync();
await process.WaitForExitAsync();
await Console.Out.WriteLineAsync(output.Trim());
return process.ExitCode == 0;
}
catch
{
return false;
}
}
static async Task<bool> PullDockerImageAsync(string imageName, string imageTag)
{
try
{
ProcessStartInfo psi = new()
{
FileName = "docker",
Arguments = $"pull {imageName}:{imageTag}",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using Process process = new() {
StartInfo = psi };
process.Start();
string output = await process.StandardOutput.ReadToEndAsync();
string error = await process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync();
await Console.Out.WriteLineAsync(output.Trim());
if (!string.IsNullOrEmpty(error))
{
Console.WriteLine(error);
}
}
catch (Exception ex)
{
Console.WriteLine($"发生错误: {ex.Message}");
return false;
}
}
}
使用方式
说明:使用该方式,需要安装好
.net8 runtime
。
2、创建并运行 C#
控制台应用程序:
- 2.1 使用
Visual Studio Code
或.NET CLI
创建一个新的控制台应用程序。 - 2.2 将上述代码复制到
Program.cs
文件中。 - 2.3 将
docker-images.txt
文件放在与Program.cs
文件相同的目录中。 - 2.4 运行应用程序:
dotnet run
通过这些步骤,上面的脚本将能够从 docker-images.txt
文件中批量下载 Docker
镜像。