解决docker容器里使用systemctl启动服务报错的问题
在docker容器里使用systemctl start xxx启动xxx服务会报如下错误:
Failed to get D-Bus connection: Unknown error -1
原因是因为在docker容器里dbus-daemon没能启动,要让dbus-daemon启动起来就得将启动命令设置为/sbin/init,让/sbin/init的进程PID为1即可,还有就是启动命令里要加一个以特权模式启动的参数--privileged,命令如下:
docker run -d -it --privileged --name "test-1" docker/gitlab-runner:1.0 /sbin/init
启动容器后,在容器里再次使用systemctl start gitlab-runner启动服务,如下:
root@16b513e68891:/# systemctl start gitlab-runner root@16b513e68891:/# systemctl status gitlab-runner ● gitlab-runner.service - LSB: gitlab-runner Loaded: loaded (/etc/init.d/gitlab-runner) Active: active (running) since Sat 2018-07-21 13:21:45 CST; 34s ago Process: 53 ExecStart=/etc/init.d/gitlab-runner start (code=exited, status=0/SUCCESS) CGroup: /docker/16b513e688915cfd5b91bda515284c1fbf50486213fe987806d083cd147ce56f/system.slice/gitlab-runner.service └─73 /usr/local/bin/gitlab-runner run --working-directory /data/gi... Jul 21 13:21:45 16b513e68891 gitlab-runner[53]: Starting GitLab Runner:. Jul 21 13:21:45 16b513e68891 systemd[1]: Started LSB: gitlab-runner. Jul 21 13:21:45 16b513e68891 gitlab-runner[73]: time="2018-07-21T13:21:45+08...0 Jul 21 13:21:45 16b513e68891 gitlab-runner[73]: time="2018-07-21T13:21:45+08..." Jul 21 13:21:45 16b513e68891 gitlab-runner[73]: time="2018-07-21T13:21:45+08...o Jul 21 13:21:45 16b513e68891 gitlab-runner[73]: time="2018-07-21T13:21:45+08...0 Jul 21 13:21:45 16b513e68891 gitlab-runner[73]: time="2018-07-21T13:21:45+08..." Jul 21 13:22:11 16b513e68891 systemd[1]: Started LSB: gitlab-runner. Hint: Some lines were ellipsized, use -l to show in full.
查阅了一些资料得知虽然上面是解决了问题,但实际上这样做并不好,因为--privileged=true相当于docker容器获得了宿主机的全权委托权限,即具有linux root用户的所有权限。这样具有非常大的安全隐患。而/sbin/init作为启动命令还可能会让docker容器内部的init与宿主机的init产生了混淆。为了解决这个问题,docker后来的版本中docker run增加了两个选项参数"--cap-add"和"--cap-drop"。具体说明如下:
--cap-add : 获取default之外的linux的权限
--cap-drop: 放弃default linux权限
所以,在运行容器时,可以不用--privileged参数的尽量不用,用--cap-add参数替代。那么启动命令可以改为:
docker run -d -it --cap-add=ALL --name "test-1" docker/gitlab-runner:1.0 /sbin/init
说是--cap-add=ALL和--privileged同等作用,不过使用上面的--cap-add=ALL来测试使用systemctl start xxx启动xxx服务依然会报“Failed to get D-Bus connection: Unknown error -1”的错误,不知是否是用错了。