gongxiangp2/scripts/save-base-images.ps1

83 lines
2.8 KiB
PowerShell

# 保存基础镜像到本地
# 用于加速后续构建,避免每次从网络拉取
param(
[switch]$Force = $false # 强制重新下载,即使本地已存在
)
$ErrorActionPreference = "Stop"
$baseImagesDir = Join-Path (Split-Path $PSScriptRoot -Parent) "base-images"
$baseImagesDir = [System.IO.Path]::GetFullPath($baseImagesDir)
# 需要保存的基础镜像列表
# 包括 Dockerfile 和 docker-compose 中使用的所有基础镜像
$baseImages = @(
"alpine:3.18" # Dockerfile 基础镜像
"redis:7-alpine" # docker-compose 中使用的 Redis 镜像
# 可以根据需要添加更多基础镜像
)
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " 保存基础镜像到本地" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "目标目录: $baseImagesDir" -ForegroundColor Yellow
Write-Host ""
# 创建目录
if (-not (Test-Path $baseImagesDir)) {
New-Item -ItemType Directory -Path $baseImagesDir -Force | Out-Null
Write-Host "已创建目录: $baseImagesDir" -ForegroundColor Green
}
$savedCount = 0
$skippedCount = 0
foreach ($image in $baseImages) {
$imageName = $image -replace ':', '-'
$tarPath = Join-Path $baseImagesDir "${imageName}.tar"
Write-Host "处理镜像: $image" -ForegroundColor Cyan
# 检查本地是否已存在
if ((Test-Path $tarPath) -and -not $Force) {
Write-Host " ✓ 本地已存在,跳过: $tarPath" -ForegroundColor Gray
$skippedCount++
continue
}
# 拉取镜像
Write-Host " 正在拉取镜像..." -ForegroundColor Yellow
docker pull $image
if ($LASTEXITCODE -ne 0) {
Write-Host " ✗ 拉取失败: $image" -ForegroundColor Red
continue
}
# 保存镜像到 tar 文件
Write-Host " 正在保存到: $tarPath" -ForegroundColor Yellow
docker save -o $tarPath $image
if ($LASTEXITCODE -ne 0) {
Write-Host " ✗ 保存失败: $image" -ForegroundColor Red
continue
}
# 获取文件大小
$fileSizeMB = (Get-Item $tarPath).Length / 1MB
$fileSizeStr = [Math]::Round($fileSizeMB, 2).ToString() + " MB"
Write-Host " ✓ 保存成功: $tarPath ($fileSizeStr)" -ForegroundColor Green
$savedCount++
Write-Host ""
}
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " 完成" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "保存: $savedCount 个镜像" -ForegroundColor Green
Write-Host "跳过: $skippedCount 个镜像" -ForegroundColor Gray
Write-Host ""
Write-Host "提示: 后续构建将自动使用这些本地镜像" -ForegroundColor Yellow
Write-Host "提示: 如需重新下载,请使用 -Force 参数" -ForegroundColor Gray