如何使用 Ubuntu18.04 在 Dockerfile 上启用 systemd

How to enable systemd on Dockerfile with Ubuntu18.04

我知道不建议在 Docker 容器上使用 Systemd,但这可能吗?

我在使用 Ansible 部署的 Ubuntu 18.04 云虚拟机上有 staging/prod 环境;

我当前的开发环境是 Ubuntu 18.04 Vagrantfile,它使用与 staging/prod

相同的 Ansible playbook.yml

现在我正在尝试用 Dockerfile 替换 Vagrantfile 用于开发,但是 Ansible playbook.yml 在应用 systemd 模块时失败。我也想在我的开发环境中安装 systemd,这样我就可以在我的 playbook.yml 本地测试更改。知道我该怎么做吗?

如果我尝试使用 Dockerfileplaybook.yml 进行构建,如下所示,我会收到错误消息 Failed to find required executable systemctl in paths

如果我将 RUN apt-get install systemd 添加到 Dockerfile 并尝试构建,我会得到一个错误 System has not been booted with systemd as init system

样本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

样本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

样本inventory:

docker-dev ansible_host=localhost ansible_connection=local

这是应该使用 docker-systemctl-replacement 脚本的完美示例。

它的开发允许 ansible 脚本以虚拟机和 docker 容器为目标。您不需要启用真正的 systemd,只需在其他受 systemd 控制的操作系统中覆盖 /usr/bin/systemctl。 docker 容器对于 ansible 来说看起来足够好,而我更习惯使用通用的 'service:' 模块而不是特定的 'systemd:' 模块。

如果它是一个选项,您也可以从 systemd 已经启用的 docker 图像开始,作为 this one available for ubuntu 18.04, and see also here.

这是一个示例 docker文件,我们从该图像开始并安装 python3.8 以满足我们的应用需求:

FROM jrei/systemd-ubuntu


# INSTALL PYTHON
RUN apt-get update -q -y
RUN apt-get install -q -y python3.8 python3-distutils curl libpq-dev build-essential python3.8-dev
RUN rm /usr/bin/python3
RUN ln -s /usr/bin/python3.8 /usr/bin/python3
RUN curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
RUN python3.8 get-pip.py
RUN pip3.8 install --upgrade pip
RUN pip3.8 install -q -r requirements.txt

RUN update-alternatives --install /usr/bin/python python /usr/bin/python3 10
ENV PYTHONPATH "${PYTHONPATH}:."

### then setting the app needs and entrypoint