Docker定制容器镜像的2种方法(推荐)

2020-06-17 06:44:43易采站长站整理

一、需求

由于在测试环境中使用了docker官网的centos 镜像,但是该镜像里面默认没有安装ssh服务,在做测试时又需要开启ssh。所以上网也查了查资料。下面详细的纪录下。在centos 容器内安装ssh后,转成新的镜像用于后期测试使用。

二、镜像定制

第一种方式(手动修改容器镜像)

1.先下载centos镜像


[root@docker ~]# docker pull centos

2.启动容器并进行配置

启动容器,


[root@docker ~]# docker run -it -d --name test-centos1 centos
d72250ecaa5e3e36226a1edd749f494d9f00eddc4143c81ac3565aa4e551791a

命令注释:-it : 进行交互式操作

     -d : 等同于 -d=true,容器将会在后台运行,不然执行一次命令后,退出后,便是exit状态了。

     –name : 容器启动后的名字,默认不指定,将会随机产生一个名字。或者使用 -name=”containers_name”

     centos:使用的镜像名称

进入容器,安装ssh server,以及配置开机启动


[root@docker ~]# docker exec -it test-centos1 /bin/bash
[root@d72250ecaa5e /]# ifconfig
bash: ifconfig: command not found

注:命令最后参数 /bin/bash: 指进入容器时执行的命令(command)

我们检查了下容器,暂时安装以下必用的软件吧 net-tools,openssh-server


[root@d72250ecaa5e /]# yum install openssh-server net-tools -y

创建ssh 所需的目录,并在根目录创建sshd 启动脚本


[root@d72250ecaa5e /]# mkdir -pv /var/run/sshd
mkdir: created directory '/var/run/sshd'

[root@d72250ecaa5e /]# cat /auto_sshd.sh
#!/bin/bash
/usr/sbin/sshd -D
[root@d72250ecaa5e /]# chmod +x /auto_sshd.sh

修改容器内root 的账户密码


[root@d72250ecaa5e /]# echo "root:iloveworld" | chpasswd

生成ssh 主机dsa 密钥(不然ssh 该容器时,会出现错误。)


[root@d72250ecaa5e /]# ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key
[root@d72250ecaa5e /]# ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key

我们加一个history记录的时间功能吧,这样方便后期查看


echo 'export HISTTIMEFORMAT="%F %T `whoami` "' >> /etc/profile

OK,配置基本完毕咯。清理命令历史纪录,之后退出容器。现在可以生成一个新的docker 镜像了。

 3.配置完成后,进行打包成新的镜像