docker导出所有镜像一键恢复(带tag)
一键备份所有docker镜像
新建脚本并赋予权限
chmod +x export_images.shsed 's/.*///' 用于从仓库名称中删除斜杠 / 前的所有字符。这样,生成的备份文件名将不包含镜像来源仓库。
#!/bin/bash
# Define the output directory
output_dir="image_backups"
# Create the output directory if it doesn't exist
mkdir -p $output_dir
# Get a list of all local Docker images
images=$(docker images --format "{{.Repository}}:{{.Tag}}")
# Loop through the list of images and export each one
for image in $images; do
# Extract the repository and tag from the image name
repository=$(echo $image | cut -d':' -f1)
tag=$(echo $image | cut -d':' -f2)
# Remove characters before the last '/' in the repository name
repository=$(echo $repository | sed 's/.*\///')
# Define the output filename
output_file="${output_dir}/${repository}_${tag}.tar"
# Export the image to the output file
docker save -o $output_file $image
done一键恢复镜像(带tag)
新建脚本并赋予权限
chmod +x import_images.sh这个脚本将批量导入指定目录中的备份文件,并将它们还原为 Docker 镜像。在还原时,脚本将使用备份文件的文件名来确定每个镜像的名称和标签,并将其导入到 Docker 中
#!/bin/bash
# Define the directory containing the backup files
backup_dir="image_backups"
# Get a list of all backup files in the directory
backup_files=$(find $backup_dir -type f -name "*.tar")
# Loop through the list of backup files and import each one
for backup_file in $backup_files; do
# Extract the repository and tag from the backup file name
filename=$(basename $backup_file)
repository=$(echo $filename | cut -d'_' -f1)
tag=$(echo $filename | cut -d'_' -f2 | cut -d'.' -f1)
# Define the image name
image_name="${repository}:${tag}"
# Import the backup file as a Docker image
docker load -i $backup_file
# Optionally, tag the imported image with its original name
docker tag $(docker images -q | head -n 1) $image_name
done版本二
- 新建导出命令
#!/bin/bash
# 获取镜像列表并将其保存到 image_list.txt 文件中
docker images --format "{{.Repository}}:{{.Tag}}" > image_list.txt
# 从镜像列表文件中逐行读取镜像名称,并导出镜像
while read -r image_name; do
# 分别将斜杠替换为破折号,冒号替换为下划线,点替换为逗号
sanitized_name="${image_name//\//-}"
sanitized_name="${sanitized_name//:/_}"
sanitized_name="${sanitized_name//./,}"
docker save -o "${sanitized_name}.tar" "$image_name"
done < image_list.txt
echo "镜像导出完成!"- 导入镜像
新建导入脚本
#!/bin/bash
# 获取当前目录下所有的 tar 归档文件
tar_files=(*.tar)
# 逐个加载恢复镜像
for tar_file in "${tar_files[@]}"; do
docker load -i "$tar_file"
done