#!/bin/bash
if [ $# -ne 1 ]; then
echo "用法: $0 <私有仓库地址>"
echo "示例: $0 registry.example.com"
exit 1
fi
if ! command -v docker; then
echo "错误: 未检测到docker命令,请确认docker是否已安装并在系统路径中"
exit 1
fi
if ! docker info; then
echo "错误: docker服务未运行,请先启动docker服务"
exit 1
fi
REGISTRY_URL=$1
WORK_DIR=$(pwd)
tar_count=$(ls -1 *.tar 2>/dev/null | wc -l)
if [ $tar_count -eq 0 ]; then
echo "错误: 当前目录下没有找到.tar格式的docker镜像文件"
exit 1
fi
temp_image_list=$(mktemp)
docker images --format "{{.Repository}}:{{.Tag}}" > /tmp/before_load.txt
echo "开始加载docker镜像文件..."
for image_file in *.tar; do
if [ -f "$image_file" ]; then
echo "正在加载 $image_file ..."
if ! docker load -i "$image_file"; then
echo "警告: 加载 $image_file 失败"
continue
fi
docker images --format "{{.Repository}}:{{.Tag}}" > /tmp/after_load.txt
comm -13 /tmp/before_load.txt /tmp/after_load.txt >> $temp_image_list
cp /tmp/after_load.txt /tmp/before_load.txt
fi
done
if [ ! -s "$temp_image_list" ]; then
echo "错误: 没有成功加载任何镜像"
exit 1
fi
echo -e "\n本次加载的镜像列表:"
cat $temp_image_list
echo -e "\n开始修改镜像标签..."
while read image; do
image_name=$(echo $image | awk -F'/' '{print $(NF-1)}')
image_tag=$(echo $image | cut -d':' -f2)
new_image="${REGISTRY_URL}/${image_name}:${image_tag}"
echo "将 $image 改为 $new_image"
if ! docker tag $image $new_image; then
echo "警告: 为 $image 添加新标签失败"
continue
fi
done < $temp_image_list
echo -e "\n修改后的镜像列表:"
docker images | grep "^${REGISTRY_URL}/" || echo "没有找到带有 ${REGISTRY_URL} 前缀的镜像"
read -p "是否需要登录私有仓库? (y/n): " login_registry
if [ "$login_registry" = "y" ] || [ "$login_registry" = "Y" ]; then
read -p "请输入用户名: " username
read -sp "请输入密码: " password
echo
if ! echo "$password" | docker login "$REGISTRY_URL" -u "$username" --password-stdin; then
echo "错误: 登录私有仓库失败"
exit 1
fi
fi
read -p "是否要推送镜像到私有仓库? (y/n): " push_images
if [ "$push_images" = "y" ] || [ "$push_images" = "Y" ]; then
echo -e "\n开始推送镜像到私有仓库..."
while read image; do
image_name=$(echo $image | awk -F'/' '{print $(NF-1)}')
image_tag=$(echo $image | cut -d':' -f2)
new_image="${REGISTRY_URL}/${image_name}:${image_tag}"
echo "正在推送 $new_image ..."
if ! docker push $new_image; then
echo "警告: 推送 $new_image 失败"
fi
done < $temp_image_list
fi
echo -e "\n操作完成!"