从docker下载默认的CentOS镜像没有开启systemd,执行systemctl命令会显示“Failed to get D-Bus connection: Operation not permitted”错误 ,如果docker创建centos7的容器涉及到systemctl服务操作,或者需要实现容器开机后自动启动服务功能。需要调整镜像并且修改镜像启动方式。
1. docker拉取centos7镜像
docker pull centos:centos7.9.2009
2. 编写dockerfile文件
vi centos.dockerfile
添加以下内容上去
FROM centos:centos7.9.2009
ENV container docker
RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == \
systemd-tmpfiles-setup.service ] || rm -f $i; done); \
rm -f /lib/systemd/system/multi-user.target.wants/*;\
rm -f /etc/systemd/system/*.wants/*;\
rm -f /lib/systemd/system/local-fs.target.wants/*; \
rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
rm -f /lib/systemd/system/basic.target.wants/*;\
rm -f /lib/systemd/system/anaconda.target.wants/*;
VOLUME [ "/sys/fs/cgroup" ]
CMD ["/usr/sbin/init"]
3. 制作镜像
docker build -t centos7.9 -f centos.dockerfile .
4. 在docker中查看镜像是否被制作好
docker images
5. 启动镜像
docker run -dit --privileged=true --name=centos7 centos7.9 /sbin/init
6.检查容器是否启动成功
docker ps -a
7.进入容器
docker exec -it centos7 /bin/bash