基础环境:
底层操作系统:CentOS 7.9
容器版本:19.03.5
Ubuntu容器镜像:20.4
拉取镜像
[root@wjy ~]# docker search ubuntu #搜索ubuntu镜像
[root@wjy ~]# docker pull ubuntu #拉取最新镜像
[root@wjy ~]# docker images #查看镜像
REPOSITORY TAG IMAGE ID CREATED SIZE
ubuntu latest d2e4e1f51132 4 weeks ago 77.8MB
[root@wjy ~]# docker tag ubuntu:latest my_ubuntu:20.4 #更换标签备用
[root@wjy ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
ubuntu 20.4 d2e4e1f51132 4 weeks ago 77.8MB
ubuntu latest d2e4e1f51132 4 weeks ago 77.8MB
启动容器
[root@wjy ~]# docker run -itd --privileged --name wjytest01 -p 10026:22 my_ubuntu:20.04 /usr/sbin/init
9568c92f6664e614a818936d3208f3291c0f596852efd47cfbc3d0695bbc3b64
默认关闭ssh,这里开启
[root@wjy ~]# docker exec -it wjytest01 /bin/bash
root@9568c92f6664:/# systemctl enable ssh
Synchronizing state of ssh.service with SysV service script with /lib/systemd/systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install enable ssh #这里大概有个十几二十秒
root@9568c92f6664:/#
重启容器大概半分钟生效,拉起了第二个容器,启动一分半左右才ssh自启才生效
[root@wjy ~]# docker logs --tail 300 ubuntu
systemd 245.4-4ubuntu3.15 running in system mode. (+PAM +AUDIT +SELINUX +IMA +APPARMOR +SMACK +SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ +LZ4 +SECCOMP +BLKID +ELFUTILS +KMOD +IDN2 -IDN +PCRE2 default-hierarchy=hybrid)
Detected virtualization container-other.
Detected architecture x86-64.
Failed to create symlink /sys/fs/cgroup/cpuacct: File exists
Failed to create symlink /sys/fs/cgroup/cpu: File exists
Failed to create symlink /sys/fs/cgroup/net_prio: File exists
Failed to create symlink /sys/fs/cgroup/net_cls: File exists
Welcome to Ubuntu 20.04.4 LTS!
网上文章给出了原因详解
–privileged 使container内的root拥有真正的root权限,不进行降权处理。否则,容器内的用户只是外部的一个普通用户,普通用户还想访问内核?让systemctl管理系统? 而且默认情况下,在第一步执行的是 /bin/bash 所以我们使用了 /usr/sbin/init覆盖/bin/bash
同时 只能使用 docker exec -it systemctl5 /bin/bash 因为 exec 可以让我们执行被覆盖掉的默认命令 /bin/bash 同时 -it 也是必须的。