使用 -it 选项时 Docker 容器退出

Sam*_*ann 7 docker dockerfile

考虑以下 Dockerfile:

FROM ubuntu:16.04

RUN apt-get update && \
    apt-get install -y apache2 && \
    apt-get clean

ENTRYPOINT ["apache2ctl", "-D", "FOREGROUND"]
Run Code Online (Sandbox Code Playgroud)

当使用命令运行容器时,容器将启动并保持运行状态,从而允许按预期从主机docker run -p 8080:80 <image-id>访问默认的 Apache 网页。https://localhost:8080但是,使用此运行命令,我无法使用 退出容器Ctrl+C,也如预期的那样,因为容器不是使用该-it选项启动的。现在,如果-it将选项添加到运行命令中,则容器在启动后立即退出。这是为什么?有没有一种优雅的方法可以让 apache 在退出时在前台运行Ctrl+C

Sam*_*ann 5

此行为是由 Apache 引起的,不是 Docker 的问题。Apache 被设计为在收到信号时正常关闭SIGWINCH。当以交互方式运行容器时,SIGWINCH信号从主机传递到容器,有效地向 Apache 发出信号以正常关闭。在某些主机上,容器可能会在启动后立即退出。在其他主机上,容器可能会保持运行状态,直到调整终端窗口大小。

容器退出后,可以通过查看 Apache 日志文件来确认这是问题的根源,如下所示:

# Run container interactively:
docker run -it <image-id>

# Get the ID of the container after it exits:
docker ps -a

# Copy the Apache log file from the container to the host:
docker cp <container-id>:/var/log/apache2/error.log .

# Use any text editor to review the log file:
vim error.log

# The last line in the log file should contain the following:
AH00492: caught SIGWINCH, shutting down gracefully
Run Code Online (Sandbox Code Playgroud)

资料来源:

  • “由于缺乏其他信号编号,并且考虑到 httpd 通常与终端分离运行,因此选择 SIGWINCH 信号来指示 httpd 正常关闭。” (来自 apache bugzilla)就像,SIGTERM 不正是针对这种情况而考虑的吗?毕竟 SIGKILL 是“立即停止,不要彻底关闭”命令 (3认同)