2.3 docker commit 创建镜像

使用 docker commit 命令制作镜像。

docker commit 命令作用

命令格式

docker commit [选项] 容器名或容器ID [仓库[:标签]]

命令别名: docker container commit

常用选项

选项
说明
-a--author
指定镜像作者(如 -a "weimz author@weimingze.com")。
-c--change
应用 Dockerfile 指令到创建的镜像(可多次使用)。
-m--message
提交消息,描述变更内容。
-p--pause
在提交过程中暂停容器(默认 true)。

在终端内使用 docker commit 命令将容器打包为镜像。

目标

示例

执行如下命令来创建镜像。

sudo docker commit \
   -a weimingze \
   -m 'docker commit 制作的第一个镜像' \
   -c 'EXPOSE 8000' \
   -c 'CMD ["python3", "-m", "http.server", "--directory", "/root/mywebsite", "8000"]' \
   -c 'WORKDIR /root' \
   my_ubuntu python_web

运行结果如下:

weimingze@mzstudio:~$ sudo docker images
REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
ubuntu       24.04     602eb6fb314b   2 months ago   78.1MB
weimingze@mzstudio:~$ sudo docker commit -a weimingze -m 'docker commit 制作的第一个镜像' -c 'EXPOSE 8000' -c 'CMD ["python3", "-m", "http.server", "--directory", "/root/mywebsite", "8000"]' my_ubuntu python_web
sha256:d0cf826ce9ffc231eebeb96c45e58b458b825bec8dd71c45992e5e6e875bf49d

可见多了一个 docker 镜像 python_web。镜像制作完成。

查看制作好的镜像。

weimingze@mzstudio:~$ sudo docker images
REPOSITORY   TAG       IMAGE ID       CREATED          SIZE
python_web   latest    d0cf826ce9ff   49 seconds ago   168MB
ubuntu       24.04     602eb6fb314b   2 months ago     78.1MB

使用 docker history 命令查看镜像制作历史记录。

weimingze@mzstudio:~$ sudo docker history python_web
IMAGE          CREATED          CREATED BY                                      SIZE      COMMENT
d0cf826ce9ff   48 minutes ago   /bin/bash                                       89.8MB    docker commit 制作的第一个镜像
602eb6fb314b   2 months ago     /bin/sh -c #(nop)  CMD ["/bin/bash"]            0B
<missing>      2 months ago     /bin/sh -c #(nop) ADD file:1d7c45546e94b90e9…   78.1MB
<missing>      2 months ago     /bin/sh -c #(nop)  LABEL org.opencontainers.…   0B
<missing>      2 months ago     /bin/sh -c #(nop)  LABEL org.opencontainers.…   0B
<missing>      2 months ago     /bin/sh -c #(nop)  ARG LAUNCHPAD_BUILD_ARCH     0B
<missing>      2 months ago     /bin/sh -c #(nop)  ARG RELEASE                  0B

docker history 查看镜像时最上层多了一层 ID 为 d0cf826ce9ff 的只读层,最后一层占用 89.8MB 的磁盘空间。