本文共 2414 字,大约阅读时间需要 8 分钟。
使用Docker Commit命令进行镜像构建
在使用Docker进行容器化开发时,有时候需要自定义构建镜像。本文将介绍如何通过 Commit 操作来完成镜像构建。
操作环境
关于镜像
容器在被销毁后会丢失所有数据。因此,应避免在容器中存储重要数据。由于基础镜像可能无法满足所有需求,自定义构建镜像变得至关重要。
运行容器
sudo docker run -it centos:7 /bin/bash
添加 ifconfig 命令
yum -y install net-toolsifconfig
Network Information:
eth0: flags=4163inet 172.17.0.2/16 brd 172.17.255.255 ether 02:42:ac:11:00:02 txqueuelen 0 RX packets 8 bytes 648 (0.7B) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 0 bytes 0 (0B) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0lo: flags=73 inet 127.0.0.1/8 lo txqueuelen 1000 RX packets 0 bytes 0 (0B) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 0 bytes 0 (0B) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
添加脚本
建议创建一个可持续运行的脚本。确保脚本存储位置在容器的 PATH 目录下,或者修改 PATH 环境变量。
vi /usr/bin/yunweijiashellwhile true; do echo yunweijia; sleep 5; doneexit
构建镜像
使用 docker commit 命令生成新镜像。
命令语法:
docker commit -c "comment" container_id image_name:version_tag
参数说明:
generator:镜像的生成者,可随意设置,无需关联原始镜像。version:镜像的版本号,可随意指定,无需匹配原始版本。示例:
sudo docker commit c84f1f4e5c37 centos:ceshi
运行后查看镜像列表:
sudo docker images
镜像列表示例如下:
REPOSITORY TAG IMAGE ID CREATED SIZEcentos ceshi adeae577d8b3 13 seconds ago 359MBhello-world latest feb5d9fea6a5 4 months ago 13.3kBcentos 7 eeb6ee3f44bd 4 months ago 204MB
使用新镜像启动容器
sudo docker run -d centos:ceshi /bin/bash -c yunweijia
查看正在运行的容器:
sudo docker ps
新容器信息示例如下:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES291ac4a08a8d centos:ceshi "/bin/bash -c yunweijia" 8 seconds ago Up 7 seconds awesome_wiles
查看容器日志:
sudo docker logs 291ac4a08a8d
进入容器查看 ifconfig:
sudo docker exec -it 291ac4a08a8d /bin/bashifconfig
Network Information:
eth0: flags=4163inet 172.17.0.3/16 brd 172.17.255.255 ether 02:42:ac:11:00:03 txqueuelen 0 RX packets 8 bytes 648 (0.7B) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 0 bytes 0 (0B) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0lo: flags=73 inet 127.0.0.1/8 lo txqueuelen 1000 RX packets 0 bytes 0 (0B) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 0 bytes 0 (0B) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
通过 Commit 方法完成镜像构建即可。
下一篇:使用 Dockerfile 构建镜像
转载地址:http://steyk.baihongyu.com/