Docker:使用 systemd 在 centos7 容器上初始化后运行命令

eal*_*eon 6 docker centos7

根据https://hub.docker.com/_/centos/ Centos7 容器必须使用 init 进程运行才能正确让 systemd 工作

Dockerfile

FROM centos:7
ENV container docker
RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == \
systemd-tmpfiles-setup.service ] || rm -f $i; done); \
rm -f /lib/systemd/system/multi-user.target.wants/*;\
rm -f /etc/systemd/system/*.wants/*;\
rm -f /lib/systemd/system/local-fs.target.wants/*; \
rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
rm -f /lib/systemd/system/basic.target.wants/*;\
rm -f /lib/systemd/system/anaconda.target.wants/*;
VOLUME [ "/sys/fs/cgroup" ]
CMD ["/usr/sbin/init"]
Run Code Online (Sandbox Code Playgroud)

我希望在调用“docker run”时能够自动运行脚本,因此我将 CMD 行更改为

COPY startup.sh /usr/local/bin/startup.sh
CMD ["/usr/sbin/init", "/usr/local/bin/startup.sh"]
Run Code Online (Sandbox Code Playgroud)

当我 docker exec'd 进入容器时,我看到了该进程

root         1     0  0 18:20 ?        00:00:00 /usr/sbin/init /usr/local/bin/startup.sh
Run Code Online (Sandbox Code Playgroud)

尽管上面的行显示了startup.sh和init,但脚本starup.sh本身从未被执行,因为该脚本应该启动几个守护进程,并且我没有看到它们在“docker run”之后运行。
当我手动运行脚本时(不是作为 CMD 行的一部分,而是在容器 shell 中实际执行它),我会看到守护进程正在运行

如何自动调用startup.sh?我不能简单地仅替换 CMD 行startup.sh,因为那样 systemd 会中断(我需要在 init 运行后调用脚本)

我尝试将 /usr/sbin/init 放入startup.sh中

即启动.sh

daemon &
daemon2 &
exec /usr/sbin/init
Run Code Online (Sandbox Code Playgroud)

但守护进程无法运行,因为 init 没有运行

如果你把

/usr/sbin/init &
daemon &
daemon2 
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为 init 的 PID 不是 1

Gui*_*eim 0

如果您确实运行服务,则只需要 systemd-init 即可。否则,您可以只运行 shell 脚本并将 daemon 和 daemon2 放在后台。

如果您真的要“systemctl start”某些东西,那么您可以避免 cgroup-mapping 和 systemd-init start ...只需使用docker-systemctl-replacement脚本。如果您愿意,它也可以作为 PID 1 运行。