通过sh脚本导入导出docker镜像

导出docker镜像save_docker_images.sh,脚本内容如下:

脚本需要两个参数,第一个参数是导出的tar包所在的目录(必传),第二个参数是要导出的包,支持模糊查询(非必传)例如:./save_all_docker_images.sh /tmp/docker_save mysql

bash 复制代码
#!/bin/bash

# 参数校验
if [ -z "$1" ]; then
    echo "Usage: $0 <export_dir> [filter_pattern]"
    exit 1
fi

export_dir="$1"
filter_pattern="${2:-.*}"  # 默认匹配所有

# 创建目录
mkdir -p "$export_dir" || {
    echo "无法创建目录: $export_dir"
    exit 1
}

# 导出镜像
# docker images --format "table {{.Repository}}\t{{.Tag}}" | 
docker images --format '{{.Repository}}\t{{.Tag}}' | \
awk -v filter="$filter_pattern" '
    BEGIN {FS="\t"}
    NR>1 && $1 ~ filter || $2 ~ filter {
        print $1":"$2
    }
' | while read -r image; do
    echo $image
    repo=$(echo "$image" | cut -d: -f1 | tr '/' '_')
    tag=$(echo "$image" | cut -d: -f2 | tr '/' '_')
    file="$export_dir/${repo}_${tag}.tar"
    
    if [ -f "$file" ]; then
        echo "跳过已存在镜像: $image"
        continue
    fi
    
    echo "导出镜像: $image"
    docker save -o "$file" "$image"
	echo "成功导出镜像: $image"
done

echo "导出完成,保存路径: $export_dir"

导入docker镜像import_docker_images.sh,脚本内容如下:

脚本需要导出的tar包所在的目录作为参数,例如:./docker_import.sh /tmp/docker_save

bash 复制代码
#!/bin/bash

# 参数校验
if [ -z "$1" ]; then
    echo "Usage: $0 <import_dir>"
    exit 1
fi

import_dir="$1"

# 遍历镜像文件
find "$import_dir" -maxdepth 1 -name "*.tar" | while read -r file; do
    # 解析文件名
    filename=$(basename "$file")
    repo_tag=${filename%.tar}
    repo=$(echo "$repo_tag" | cut -d'_' -f1 | tr '_' '/')
    tag=$(echo "$repo_tag" | cut -d'_' -f2-)
		
    # 检查镜像是否存在
    # if docker images -q "$repo:$tag" >/dev/null 2>&1; then
    if  [ -n "$(docker images -q $repo:$tag 2>/dev/null)" ];  then
        echo "跳过已存在镜像: $repo:$tag"
        continue
    fi
    
    echo "导入镜像: $repo:$tag"
    docker load -i "$file"
	echo "导入镜像成功: $repo:$tag"
done

echo "导入完成"
相关推荐
边疆.11 小时前
【Linux】文件系统
linux·运维·服务器·磁盘·文件系统·软硬链接
DevangLic11 小时前
【win的实用官方工具集合】解决:该设备正在使用中,请关闭所有。。。
运维·学习·工具
java_logo11 小时前
Milvus GUI ATTU Docker 容器化部署指南
运维·数据库·docker·容器·eureka·milvus
盛满暮色 风止何安11 小时前
负责均衡的理解
运维·服务器·网络·网络协议·系统安全·安全架构
wyjcxyyy12 小时前
2025polar冬季赛复盘(WEB,MISC)
运维·服务器
weixin_4488557712 小时前
自动化构建、测试、部署(上)
运维·自动化
G_Cloudpipe12 小时前
Nginx 服务器部署
运维·服务器·nginx
AttaGain12 小时前
GitLab数据备迁移及系统升级
运维·服务器·gitlab
❥ღ Komo·12 小时前
K8s Secrets:敏感数据安全存储指南
安全·容器·kubernetes
眠晚晚12 小时前
云上攻防-Docker-堡垒机安全详解
安全·web安全·网络安全·docker·容器