备份还原 本地所有的Docker 镜像并且在另一台机器上还原
备份命令 并且显示进度 backup_docker_images.sh
sudo yum install jq
chmod +x backup_docker_images.sh
sudo ./backup_docker_images.sh
#!/bin/bash
# 指定备份目录
backup_dir="/app/dockerImageBackup/Images"
# 创建备份目录,如果不存在的话
mkdir -p $backup_dir
# 获取所有镜像的 ID
image_ids=$(docker images -q)
# 计算镜像的总数
total_images=$(echo $image_ids | wc -w)
# 初始化进度计数器
current_image=1
# 遍历每个镜像
for image_id in $image_ids
do
# 获取镜像的所有信息
image_info=$(docker inspect $image_id)
# 获取镜像的名字和标签
image_names=$(echo $image_info | jq -r '.[0].RepoTags | join(",")')
# 如果镜像没有名字或标签,尝试从 RepoDigests 获取
if [ "$image_names" == "null" ]; then
image_names=$(echo $image_info | jq -r '.[0].RepoDigests[0]' | cut -d '@' -f1)
fi
# 使用 ID 作为文件名
image_file="$image_id.tar"
# 打印开始保存的信息
echo "Saving image $current_image of $total_images: $image_file"
# 保存镜像到文件
docker save $image_id -o "$backup_dir/$image_file"
# 保存镜像信息到文件
echo $image_info > "$backup_dir/$image_id.json"
# 打印完成保存的信息
echo "Saved image $current_image of $total_images: $image_file"
# 更新进度计数器
current_image=$((current_image + 1))
done
还原所有的镜像
tar -czf /path/to/app.tar.gz /app
tar -xzf app.tar.gz -C /app -p
chmod +x load_docker_images.sh
sudo ./load_docker_images.sh
#!/bin/bash
# 指定备份目录
backup_dir="/app/dockerImageBackup/Images"
# 遍历备份目录下的所有 .tar 文件
for tar_file in $backup_dir/*.tar
do
# 获取镜像的 ID
image_id=$(basename $tar_file .tar)
# 打印开始加载的信息
echo "Loading image: $image_id"
# 加载镜像
docker load -i $tar_file
# 打印完成加载的信息
echo "Loaded image: $image_id"
# 获取镜像的详细信息
image_info=$(cat "$backup_dir/$image_id.json")
# 获取镜像的名字和标签
image_names=$(echo $image_info | jq -r '.[0].RepoTags | join(",")')
# 如果镜像没有名字或标签,尝试从 RepoDigests 获取
if [ -z "$image_names" ]; then
echo "Image names is null, trying to get from RepoDigests..."
image_names=$(echo $image_info | jq -r '.[0].RepoDigests[0]' | cut -d '@' -f1)
echo "Image names from RepoDigests: $image_names"
fi
# 使用 docker tag 为镜像添加名字和标签
for image_name in $(echo $image_names | tr "," "\n")
do
docker tag $image_id $image_name
echo "Tagged image: $image_id as $image_name"
done
done
sudo curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
docker-compose --version