Docker镜像批量导出和导入脚本

批量导出

#!/bin/bash  
  
# 设置导出镜像的目录  
EXPORT_DIR="/root/images"  
  
# 确保导出目录存在  
mkdir -p "$EXPORT_DIR"  
  
# 获取所有的镜像并导出  
IMAGES=$(docker images --format '{{.Repository}}:{{.Tag}}')  
  
# 遍历所有的镜像  
for IMAGE in $IMAGES; do  
    # 分割镜像仓库名和标签  
    IFS=":" read -r REPOSITORY TAG <<< "$IMAGE"  
      
    # 将仓库名中的斜杠替换为下划线  
    SAFE_REPOSITORY=${REPOSITORY//\//_}  
      
    # 构造导出文件的名称  
    EXPORT_FILE="${SAFE_REPOSITORY}_${TAG}.tar"  
    EXPORT_PATH="$EXPORT_DIR/$EXPORT_FILE"  
      
    # 检查镜像是否存在,如果存在则导出  
    if docker image inspect "${REPOSITORY}:${TAG}" >/dev/null 2>&1; then  
        docker save -o "$EXPORT_PATH" "${REPOSITORY}:${TAG}"  
        echo "Exported ${REPOSITORY}:${TAG} to $EXPORT_PATH"  
    else  
        echo "Error: ${REPOSITORY}:${TAG} does not exist"  
    fi  
done

echo "Export process completed."

批量导入

#!/bin/bash  
  
# 设置包含要导入镜像的 .tar 文件的目录  
IMPORT_DIR="/root/images"  
  
# 检查目录是否存在  
if [ ! -d "$IMPORT_DIR" ]; then  
    echo "Error: Directory $IMPORT_DIR does not exist."  
    exit 1  
fi  
  
# 遍历目录下的所有 .tar 文件并导入  
for TAR_FILE in "$IMPORT_DIR"/*.tar; do  
    if [ -f "$TAR_FILE" ]; then  
        echo "Importing $TAR_FILE..."  
        docker load -i "$TAR_FILE"  
        if [ $? -eq 0 ]; then  
            echo "Successfully imported $TAR_FILE"  
        else  
            echo "Failed to import $TAR_FILE"  
        fi  
    fi  
done  
  
echo "Import process completed."
posted @ 2024-03-28 16:37  wanghongwei-dev  阅读(463)  评论(0编辑  收藏  举报