今天写一篇文章讲一下如何在Docker中运行CentOS,并且配置SSH连接。
运行CentOS
在hub.docker.com搜索 centos,第一个结果就是我们使用的 centos 基础镜像。
![Docker运行CentOS完全教程-程序旅途](https://www.chengxulvtu.net/wp-content/uploads/2019/09/2019092715131366.png)
在详情里可以看到支持的tags
![Docker运行CentOS完全教程-程序旅途](https://www.chengxulvtu.net/wp-content/uploads/2019/09/2019092715135182.png)
我们直接使用下面的命令将centos运行起来
docker run -itd --privileged centos /usr/sbin/init
为什么不用 docker run -itd centos /bin/bash 后面再解释
通过 docker ps 查看centos容器已经运行起来了
![Docker运行CentOS完全教程-程序旅途](https://www.chengxulvtu.net/wp-content/uploads/2019/09/2019092715154888.png)
通过
docker attach <container-id>
docker exec -it <container-id> /bin/bash
进入容器。
容器Id 使用前4位即可。
安装SSH
执行下面的命令安装SSH
yum install -y openssh-server
![Docker运行CentOS完全教程-程序旅途](https://www.chengxulvtu.net/wp-content/uploads/2019/09/2019092715191026.png)
修改root用户密码
passwd root
![Docker运行CentOS完全教程-程序旅途](https://www.chengxulvtu.net/wp-content/uploads/2019/09/2019092715193268.png)
启动ssh服务
systemctl start sshd.service
配置ssh 开机启动
systemctl enable sshd.service
查看 ssh 状态
systemctl status sshd.service
![Docker运行CentOS完全教程-程序旅途](https://www.chengxulvtu.net/wp-content/uploads/2019/09/2019092715202497.png)
如果上面使用的docker run -itd centos /bin/bash 启动容器,这里使用systemctl是会报错的。
使用快捷键 ctrl + p, ctrl+ q 退出容器
提交镜像
使用下面的命令提交镜像
docker commit <container-id> <image-name>
container-id 可以通过 docker ps -a 查看
image-name 是新镜像的名字
使用 docker images 就可以看到刚刚提交的新镜像
![Docker运行CentOS完全教程-程序旅途](https://www.chengxulvtu.net/wp-content/uploads/2019/09/2019092715215476.png)
使用新镜像运行centos
执行下面的命令使用新镜像运行centos
docker run -itd --privileged -p 50001:22 cxlt-centos /usr/sbin/init
这里将本机的50001端口映射到容器的22端口
所以在本机使用如下命令就可以ssh到容器了。
ssh root@<本机ip> -p 50001
![Docker运行CentOS完全教程-程序旅途](https://www.chengxulvtu.net/wp-content/uploads/2019/09/2019092715231293.png)