Search code examples
dockerubuntusystemd

How to enable systemd on Dockerfile with Ubuntu18.04


I know Systemd is not recommended on Docker containers but is it possible?

I have staging/prod environments on Ubuntu 18.04 cloud VMs deployed with Ansible;

My current dev environment is a Ubuntu 18.04 Vagrantfile that uses the same Ansible playbook.yml of staging/prod

Now I'm trying to replace the Vagrantfile with a Dockerfile for development but the Ansible playbook.yml fails when applying systemd modules. I would like to have systemd on my dev environment as well so that I can test changes on my playbook.yml local. Any idea how I can do it?

If I try to build with Dockerfile and playbook.yml as below, I get an error Failed to find required executable systemctl in paths.

If I add RUN apt-get install systemd to Dockerfile nd try to build, I get an error System has not been booted with systemd as init system

Sample Dockerfile:

FROM ubuntu:18.04

ADD . /app
WORKDIR /app

# Install Python3 pip used to install Ansible
RUN apt-get update && apt-get install -y \
  python3-pip \

# Install Ansible
RUN pip3 install --trusted-host pypi.python.org ansible
RUN ansible-playbook playbook.yml -i inventory

EXPOSE 80

Sample playbook.yml:

---
- name: Ansible playbook to setup dev environment 
  hosts: all
  vars:
    ansible_python_interpreter: "/usr/bin/python3"
    debug: True
  become: yes
  become_method: sudo
  tasks:
    - name: Copy App Gunicorn systemd config
      template:
        src: app_gunicorn.service
        dest: /etc/systemd/system/

    - name: Enable App Gunicorn on systemd
      systemd: state=started name=app_gunicorn

Sample inventory:

docker-dev ansible_host=localhost ansible_connection=local

Solution

  • That's a perfect example where the docker-systemctl-replacement script should be used.

    It has been developed to allow ansible scripts to target both virtual machines and docker containers. You do not need to enable a real systemd, just overwrite /usr/bin/systemctl in operating systems that are otherwise under systemd control. The docker container will then look good enough for ansible, whereas I am more used to use the general 'service:' module instead of the specific 'systemd:' module.