Attempts at running a service from within a CentOS 7 container fail with “Failed to get D-Bus connection: Operation not permitted”
The first pass would probably be to get the centos/systemd base container and build on that, but this was not an option for me (for bureaucratic reasons that aren’t very exciting or worth getting into).
Fortunately, the official centos image has some documentation on how to get systemd enabled in a Docker container, which didn’t work for me (I got an error
[!!!!!!] Failed to mount API filesystems, freezing when trying to run it as-is), but that was useful as a baseline for figuring out how to get the various bits I needed into an existing Dockerfile with some docker-compose yaml for extra flavour.
The big “ah-ha” moment for me was when I finally understood that you have to enable your service before calling
/usr/sbin/init since this program was the magic sauce that started the service in question.
I created a demo repo, the Dockerfile there looks like this:
You can build this image and run a container by executing the following commands manually (from within the dir that contains the Dockerfile):
docker build --rm -t centos7-systemd-docker-demo .
docker run -tid -v /sys/fs/cgroup:/sys/fs/cgroup:ro --cap-add SYS_ADMIN -p 80:80 --name centosdemo centos7-systemd-docker-demo
--cap-add option passed to the run command!
Once your container is running, confirm that the httpd service is live by logging into the container:
docker exec -it centosdemo /bin/bash
and checking the status:
[root@bd3bfb7520b6 /]# systemctl status httpd
● httpd.service – The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
Active: active (running) since Thu 2018-03-01 01:34:59 UTC; 48s ago
Main PID: 18 (httpd)
Status: “Total requests: 0; Current requests/sec: 0; Current traffic: 0 B/sec”
├─18 /usr/sbin/httpd -DFOREGROUND
├─20 /usr/sbin/httpd -DFOREGROUND
├─21 /usr/sbin/httpd -DFOREGROUND
├─22 /usr/sbin/httpd -DFOREGROUND
├─23 /usr/sbin/httpd -DFOREGROUND
└─24 /usr/sbin/httpd -DFOREGROUND
Mar 01 01:34:59 bd3bfb7520b6 systemd: Starting The Apache HTTP Server…
Mar 01 01:34:59 bd3bfb7520b6 httpd: AH00558: httpd: Could not reliably d…e
Mar 01 01:34:59 bd3bfb7520b6 systemd: Started The Apache HTTP Server.
Hint: Some lines were ellipsized, use -l to show in full.
If you are more inclined to using docker-compose, here are the above run commands nicely wrapped up: