下载 CentOS 镜像

docker pull centos:7.6.1810

查看镜像

[root@node01 ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
centos 7.6.1810 f1cb7c7d58b7 2 years ago 202MB
[root@node01 ~]#

创建容器

docker run -d --name centos76 -h centos76  \
-p 2222:22 -p 3387:3389 \
--privileged=true \
centos:7.6.1810 /usr/sbin/init

进入容器

docker exec -it centos76  /bin/bash
  • 实际操作:
[root@node01 ~]# docker exec -it centos76  /bin/bash
[root@centos76 /]#
[root@centos76 /]#
[root@centos76 /]# ifconfig
bash: ifconfig: command not found
  • 可以看到基本命令都用不了, 需要安装一些常用工具

安装常用工具并做基本配置

## 下载基础源
curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo

## 配置epel源
curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
sed -i -e '/mirrors.cloud.aliyuncs.com/d' -e '/mirrors.aliyuncs.com/d' /etc/yum.repos.d/CentOS-Base.repo

## 刷新
yum clean all
yum makecache

## 修改时区
#docker cp /usr/share/zoneinfo/Asia/Shanghai centos76pg:/etc/localtime
rm -f /etc/localtime
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
timedatectl set-timezone "Asia/Shanghai"
timedatectl set-ntp true

# 安装 ssh 软件
yum install -y openssh-clients openssh-server initscripts net-tools sudo which

# 允许远程登录
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
sed -i '/^#PermitRootLogin/cPermitRootLogin yes' /etc/ssh/sshd_config
sed -i '/^UsePAM/cUsePAM no' /etc/ssh/sshd_config

# 启动sshd服务
systemctl restart sshd

# 修改密码
echo "root:lxm123" | chpasswd
  • 测试是否可以通过 主机的2222端口连接到docker容器

注意下面的 172.18.115.101 是我主机ip地址

ssh root@172.18.115.101 -p 2222
  • 实际操作结果演示
[root@node01 ~]# ssh root@172.18.115.101 -p 2222
The authenticity of host '[172.18.115.101]:2222 ([172.18.115.101]:2222)' can't be established.
ECDSA key fingerprint is SHA256:VaWY6jJGmWfuSwgnhy5/g5Xb5+rnzYwVY5il0cHKRMg.
ECDSA key fingerprint is MD5:39:65:f2:b7:db:37:10:a2:dd:c9:83:b8:ed:27:22:27.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[172.18.115.101]:2222' (ECDSA) to the list of known hosts.
root@172.18.115.101's password:
[root@centos76 ~]# hostname
centos76

将容器导出为镜像 centos76:1.0

[root@node01 ~]# docker commit centos76 lxm_centos76:1.0
sha256:7d50140fddb98f74703d86f620df3a3fb3fdcb1ece254906348acbc29cfe4472
[root@node01 ~]#

使用 centos76:1.0 创建一个的容器

docker run -d --name node01 -h node01 \
-p 5222:22 \
--privileged=true \
lxm_centos76:1.0 /usr/sbin/init
  • 实际操作演示
[root@node01 ~]# docker run -d --name node01 -h node01 \
> -p 5222:22 \
> --privileged=true \
> lxm_centos76:1.0 /usr/sbin/init
14e5074f4e8b9758d3abeccfb1cdb0f7cb6444f9c6bfeb74ed883ec206e9d825
[root@node01 ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
14e5074f4e8b lxm_centos76:1.0 "/usr/sbin/init" 3 seconds ago Up 2 seconds 3389/tcp, 0.0.0.0:5222->22/tcp, :::5222->22/tcp node01
e479dd6f32a5 centos:7.6.1810 "/usr/sbin/init" 12 minutes ago Up 11 minutes 0.0.0.0:2222->22/tcp, :::2222->22/tcp, 0.0.0.0:3387->3389/tcp, :::3387->3389/tcp centos76
[root@node01 ~]#