【问题标题】:Is it possible to switch process using PID 1 in a container?是否可以在容器中使用 PID 1 切换进程?
【发布时间】:2021-05-11 05:50:03
【问题描述】:

我有一个 Pid 1 问题。好的,所以为了解释,我需要专注于我对问题的表述。

我有一项服务,它依赖于 hostid 和生成的与 hostid 匹配的许可证文件才能运行。我不知道hostid是如何产生的。 如果该服务没有有效的许可证,则进程将关闭。 所以我无法将这个简单的服务容器化。

但是,如果我有另一个进程首先运行,例如用于设置许可文件和查询 hostid 的 API,该怎么办?然后这个 api 可以将许可文件设置到位。但现在到了棘手的部分,我如何切换运行 PID 1 的进程?因为服务需要以 PID 1 运行。

我正在考虑将 PID 1 缩写为 bash 循环,该循环首先启动 API,然后在 API 退出时启动服务。

这可能吗?

您将如何创建 bash 循环?

【问题讨论】:

    标签: containers podman containerd


    【解决方案1】:

    C execve(2) 函数将当前进程替换为新进程;新进程保留有效用户 ID 等属性,并且具有相同的进程 ID。 Bourne shell 包含一个 exec 内置函数,可以做同样的事情。

    Docker 映像中的一个常见模式是使用入口点包装脚本进行首次设置。如果容器同时具有入口点和命令,the command gets passed as arguments to the entrypoint。所以你可以写一个像这样的脚本:

    #!/bin/sh
    
    # Do whatever's needed to get the license
    /opt/myapp/bin/get_license
    
    # Then run the command part
    #   exec replaces this script, so it will have pid 1
    #   "$@" is the command-line arguments
    exec "$@"
    

    在 Dockerfile 中,将 ENTRYPOINT 设置为此包装器,并将 CMD 设置为运行真正的服务。

    # Run the script above
    # ENTRYPOINT must have JSON-array syntax in this usage
    ENTRYPOINT ["/opt/myapp/bin/start_with_license"]
    
    # Say the normal thing you want the container to do
    # CMD can have either JSON-array or shell syntax
    CMD ["/opt/myapp/bin/server", "--foreground"]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-04
      • 1970-01-01
      • 2022-08-13
      • 2015-03-05
      • 1970-01-01
      相关资源
      最近更新 更多