1.将容器保存为镜像(先把容器停止运行不然会有问题)

docker commit 容器名称 保存的新镜像名称

操作:
  1. [root@VM_0_7_centos nexus]# docker commit nexus nexus-z
  2. sha256:511575baf7897e13c17da89e470b92a522785e2a9e61f32759eb49cc61a4140e
  3. [root@VM_0_7_centos nexus]# docker images
  4. REPOSITORY TAG IMAGE ID CREATED SIZE
  5. nexus-z latest 511575baf789 11 seconds ago 599MB

2.将镜像打为压缩包

docker save -o 打包后的文件名称 镜像名称

操作:
[root@VM_0_7_centos nexus]# docker save nexus-z -o ./nexus-z.tar
[root@VM_0_7_centos nexus]# ll
total 596132
-rw-------  1 root root 610430976 Dec 31 16:33 nexus-z.tar

3.将打包后的镜像压缩包和挂载的文件夹迁移(Mac可以使用Transmit工具)

4.镜像恢复

docker load -i 镜像保存的tar包

操作:

[root@localhost nexus]# docker load -i ./nexus-z.tar

5.修改docker-compose.yml文件

version: '3.7'
services:
  nexus:
    restart: always
    image: nexus-z #修改这里依赖的镜像
    container_name: nexus
    ports:
      - 8081:8081
    volumes:
      - /usr/local/docker/nexus/data:/nexus-data

6.根据docker-compose生成容器

[root@localhost nexus]# docker-compose up -d
Creating network "nexus_default" with the default driver
Creating nexus ... done

通过查看日志发现没有读写文件权限(Permission denied):
[root@localhost nexus]# docker logs 57ee
Warning:  Cannot open log file: ../sonatype-work/nexus3/log/jvm.log
Warning:  Forcing option -XX:LogFile=/tmp/jvm.log
OpenJDK 64-Bit Server VM warning: Cannot open file ../sonatype-work/nexus3/log/jvm.log due to Permission denied
java.io.FileNotFoundException: ../sonatype-work/nexus3/tmp/i4j_ZTDnGON8hezynsMX2ZCYAVDtQog=.lock (Permission denied)

修改文件夹操作权限
[root@localhost nexus]# chmod -R 777 data
[root@localhost nexus]# ll
total 596132
drwxrwxrwx. 16  777 root      4096 Dec 31 16:55 data

容器的的导出和导入

导出容器
如果要导出本地某个容器,可以使用 docker export 命令。

$ sudo docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                    PORTS               NAMES
7691a814370e        ubuntu:14.04        "/bin/bash"         36 hours ago        Exited (0) 21 hours ago                       test
$ sudo docker export 7691a814370e > ubuntu.tar

这样将导出容器快照到本地文件。
导入容器快照
可以使用 docker import 从容器快照文件中再导入为镜像,例如

$ cat ubuntu.tar | sudo docker import - test/ubuntu:v1.0
$ sudo docker images
REPOSITORY          TAG                 IMAGE ID            CREATED              VIRTUAL SIZE
test/ubuntu         v1.0                9d37a6082e97        About a minute ago   171.3 MB

此外,也可以通过指定 URL 或者某个目录来导入,例如
$sudo docker import http://example.com/exampleimage.tgz example/imagerepo
*注:用户既可以使用 docker load 来导入镜像存储文件到本地镜像库,也可以使用 docker import 来导入一个容器快照到本地镜像库。这两者的区别在于容器快照文件将丢弃所有的历史记录和元数据信息(即仅保存容器当时的快照状态),而镜像存储文件将保存完整记录,体积也要大。此外,从容器快照文件导入时可以重新指定标签等元数据信息。