通过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 "导入完成"
相关推荐
Java后端的Ai之路1 分钟前
Linux端口进程查找与终止教程
linux·运维·服务器
busy dog~乌鸦~31 分钟前
【THM-题目答案】:Web Fundamentals-How The Web Works-DNS in Detail: Domain Hierarchy
运维·web安全·网络安全·系统安全
mounter6252 小时前
深度解析:Linux 内核为何要移除“直接映射” (Direct Map)?
linux·运维·服务器·security·linux kernel·direct mem map
AC赳赳老秦2 小时前
HR必备:OpenClaw批量筛选简历、发送面试通知,优化招聘流程
运维·人工智能·python·eclipse·github·deepseek·openclaw
NineData2 小时前
NineData亮相香港国际创科展InnoEX 2026,以AI加速布局全球市场
运维·后端
another heaven3 小时前
【Docker/虚拟机 深度对比Docker与虚拟机:原理、区别与最佳使用场景】
运维·docker·容器
带娃的IT创业者3 小时前
零停机迁移:如何将服务器成本从 $1432 降至 $233
运维·服务器·网络·成本优化·服务器迁移·零停机·hetzner
独自归家的兔3 小时前
2026年4月16日 Ubuntu系统 Docker 的安装与配置
运维·docker·容器
舒一笑3 小时前
Docker 离线镜像导入后变成 <none>:<none>?一文讲透原因、排查与正确打包姿势
后端·docker·容器
福老板的生意经4 小时前
从成本失控到ROI翻倍:企业数字化营销投放的落地路径与工具选型指南
大数据·运维·人工智能