通过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 "导入完成"
相关推荐
mengge.cloud23 分钟前
1019Namespace ,Contexts ,Kubernetes Pod
运维·服务器·网络·云原生·容器·kubernetes·云计算
江湖有缘24 分钟前
Docker实战 | 使用Docker部署Imagor Studio图片编辑工具
java·docker·eureka
Xxtaoaooo38 分钟前
私人日记不想散落在多个App?我用DailyTxT把记录、搜索和图片都放进自己的NAS
docker·nas·dailytxt
吴声子夜歌1 小时前
Docker入门与实战——Etcd(高可用的键值数据库)
数据库·docker·etcd
mklpo1471 小时前
在 安卓手机 上通过termux运行 gentoo 和 宝塔面板。2026.10.19
linux·运维·服务器
flytalei1 小时前
从 Docker Compose 到 K3s:逐浪博客 MySQL 数据迁移实战与一致性验证
mysql·docker·容器
周周爱喝粥呀1 小时前
详细教程:在 Docker 中部署 PostgreSQL 并使用 pgAdmin 可视化管理
docker·postgresql·容器
xatu1 小时前
ubuntu容器在redhat系统下使用大模型API问题
linux·运维·ubuntu
雪落漂泊3 小时前
Linux基础开发工具(三)gcc/g++与make/makefile篇
linux·运维·服务器
Sayai3 小时前
Neo4j 社区版高可用实战:DRBD 块级复制 + Keepalived 虚拟 IP 冷备切换(附启停 SOP 与脑裂防范)
运维·neo4j·keepalived·高可用·drbd