码头CMD末尾的`tail -f`输出未显示

sim*_*905 13 docker dockerfile

使用Docker for Mac 1.13.1和以下Dockerfile:

FROM ubuntu:latest
MAINTAINER docker@ekito.fr

#Install packages and clean downloaded packages in the lowest layer
RUN apt-get update && apt-get -y install cron && rm -rf /var/lib/apt/lists/*

# Add crontab file in the cron directory
ADD crontab /etc/cron.d/hello-cron

# Give execution rights on the cron job and create the log file to tail in the next layer
RUN chmod 0644 /etc/cron.d/hello-cron && touch /var/log/cron.log

# Run the command on container startup
CMD echo "starting" && echo "continuing" && (cron) && echo "tailing..."  && tail -f /var/log/cron.log
Run Code Online (Sandbox Code Playgroud)

使用contab文件:

* * * * * root echo "Hello world `date`" >> /var/log/cron.log 2>&1
# Don't remove the empty line at the end of this file. It is required to run the cron job
Run Code Online (Sandbox Code Playgroud)

当我构建并运行它时:

docker build -t docker-cron-master .
docker run docker-cron-master
Run Code Online (Sandbox Code Playgroud)

我看到输出:

docker run docker-cron-master
starting
continuing
tailing...
Run Code Online (Sandbox Code Playgroud)

如果我等一下,tail -f输出就不会出现.然而,如果我登录到正在运行的容器并拖尾文件,我可以看到内容:

$ docker exec -it 4eda6b1fc6ce bash
root@4eda6b1fc6ce:/# tail -f /var/log/cron.log
Hello world Fri May  5 09:53:01 UTC 2017
Hello world Fri May  5 09:54:01 UTC 2017
Run Code Online (Sandbox Code Playgroud)

我尝试在CMD的末尾添加另一个echo,看看它是否只是最后一个命令STDOUT被吞下但是没有帮助.

我发布的代码是在github上的https://github.com/simbo1905/docker-cron

谢谢!

BMi*_*tch 15

docker文件系统使用copy-on-write和它的分层union fs.因此,当您写入图像的一部分文件时,它将首先将该文件的副本复制到容器文件系统,该文件系统是所有图像层之上的层.

这意味着当您在/var/log/cron.log中添加一行时,它将在文件系统中获得一个新的inode,并且该tail命令所遵循的文件不再是您在docker exec进入容器时看到的文件.您可以通过一个小的更改来解决这个问题,以便在文件中附加"nothing",这也会修改强制写入时复制的上一个更新时间戳:

CMD echo "starting" && echo "continuing" && (cron) \
 && echo "tailing..." && : >> /var/log/cron.log && tail -f /var/log/cron.log
Run Code Online (Sandbox Code Playgroud)

我在这里整理了一个关于这个问题的要点,并提供了更多细节:https://gist.github.com/sudo-bmitch/f91a943174d6aff5a57904485670a9eb