报错原因
使用Docker运行容器后,直接执行systemctl命令时,会出现如下报错提示我们:当前系统尚未以systemd作为初始系统 (PID 1)引导。无法操作。
解决方法
使用docker-systemctl-replacement-master
中的systemctl.py
文件替换容器中的systemctl
文件
下载地址:https://github.com/gdraheim/docker-systemctl-replacement/blob/master/files/docker/systemctl.py
我这里以centos为例,启动容器
docker run -it centos
1)启动后是不能直接使用systemctl
命令的
2)配置yum源,默认拉取的为centos8的镜像,由于yum源不可用,需要手动替换
rm -rf /etc/yum.repos.d/* #清空默认源
#下载阿里云源到本地
curl -o /etc/yum.repos.d/centos8.repo https://mirrors.aliyun.com/repo/Centos-8.repo
#重建缓存
yum clean all && yum makecache
3)安装Python2(默认没有安装python2,需要手动安装一下)
*#检查是否安装python2*
rpm -q python2
*#安装python2*
yum install python2 -y
4)查找当前系统的systemctl
文件在什么地方(使用whereis
或type
命令)
type systemctl
whereis systemctl
5)找到后将systemctl
文件内容替换为上面下载的systemctl.py
的文件内容
#备份源文件
cp -r /usr/bin/systemctl /usr/bin/systemctl.bak
#清空文件内容
>/usr/bin/systemctl
使用vi编辑器打开文件,粘贴systemctl.py
的内容后保存退出即可
测试是否生效
在容器内安装Apache服务,启动测试
yum install httpd -y
systemctl status httpd
systemctl start httpd
可以看到执行systemctl
命令时已经不再报错
扩展
如果需要在容器中使用systemctl
,可以使用如下的Dockefile文件,直接将systemctl.py
打包到镜像中。
执行docker build -t 镜像名:tag .
打包为镜像文件
运行打包好的镜像
docker run -it centos8:6.2
此时容器可以正常使用systemctl
来启动服务了,无需额外配置