将 Docker 镜像从服务器A迁移到服务器B的方法
在日常工作中,我们有时会需要将服务器 A上的镜像上传至服务器B上,下面给出具体操作方式,以镜像 postgres:15
为例进行讲解。
首先在服务器A上拉取 镜像 postgres:15
,命令如下:
docker pull postgres:15
下面再将服务器A上的postgres:15
镜像上传至服务器B,主要有以下几种方式:
方法1:使用 Docker Save 和 Load(推荐)
- 在服务器A上保存镜像为tar文件:
docker save -o postgres15.tar postgres:15
- 将tar文件传输到服务器B(使用scp或其他方式):
scp postgres15.tar user@serverB:/path/to/destination
- 在服务器B上加载镜像:
docker load -i postgres15.tar
注意:这里可能出现报错:
permission denied while trying to connect to the Docker daemon socket >at unix:///var/run/docker.sock: Post "http://%2Fvar%2Frun%2Fdocker.sock/v1.44/images/load?quiet=0": dial >unix /var/run/docker.sock: connect: permission denied
解决方式:使用 sudo 权限执行 docker load 命令
sudo docker load -i postgres15.tar
- 在服务器B上查看镜像:
docker images
方法2:使用 Docker Hub 作为中转
- 在服务器A上登录Docker Hub:
docker login
- 给镜像打标签并推送(需要你有Docker Hub账户):
docker tag postgres:15 yourusername/postgres:15
docker push yourusername/postgres:15
- 在服务器B上拉取镜像:
docker pull yourusername/postgres:15
方法3:使用私有仓库中转(内网环境)
如果你有私有Docker仓库(如Harbor等):
- 在服务器A上打标签并推送:
docker tag postgres:15 your-registry.com/your-project/postgres:15
docker push your-registry.com/your-project/postgres:15
- 在服务器B上拉取:
docker pull your-registry.com/your-project/postgres:15
注:私有仓库中转的方式很适合于服务器无法连接外网的情况,通过内部网络(私有仓库)进行中转。