通过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 "导入完成"
相关推荐
曦樂~1 分钟前
Symmetric Ciphers对称加密
运维·服务器
mister_guo6 分钟前
Elasticsearch:原理、Docker 安装与常用命令
大数据·运维·elasticsearch
刚入门的大一新生23 分钟前
Linux-Ext系列文件系统
linux·运维·服务器
灯澜忆梦1 小时前
【docker】#4 | Docker 自定义镜像与 Dockerfile
运维·docker·容器
SKH.1 小时前
Linux驱动-led、beep
linux·运维·单片机
TTATTC1 小时前
Android 浏览器死活不弹证书框的那天,我用 .NET MAUI 给 WebView 写了一个 mTLS 拦截器
docker·开源
TTATTC1 小时前
百万行 Trace 交给 AI,方向和验证留给人,一套还原自定义 VMP 保护的分工方法
docker·开源
mklpo1472 小时前
为不支持sse4.2命令集的老旧设备制作Win11 26H2系统镜像,2026-10-11。
运维·windows·python
TTATTC2 小时前
从 proxy_pass 末尾斜杠到 WebAssembly 预压缩:深挖 Nginx 生产环境四大高频踩坑点
docker·开源
TTATTC2 小时前
消灭 AI 编程助手的幻觉代码:拆解 Google 官方文档 MCP 与三大云厂商知识检索架构
docker·开源