Docker ubuntu cron 尾部日志不可见

Rob*_*_UK 6 cron logging tty docker docker-compose

尝试运行具有 cron 调度的 docker 容器。但是我不能让它输出日志。

我正在使用 docker-compose。

docker-compose.yml

---
version: '3'
services:
  cron:
    build:
      context: cron/
    container_name: ubuntu-cron
Run Code Online (Sandbox Code Playgroud)

定时/Dockerfile

FROM ubuntu:18.10

RUN apt-get update
RUN apt-get update && apt-get install -y cron 

ADD hello-cron /etc/cron.d/hello-cron

# Give execution rights on the cron job
RUN chmod 0644 /etc/cron.d/hello-cron

# Create the log file to be able to run tail
RUN touch /var/log/cron.log

# Run the command on container startup
CMD cron && tail -F /var/log/cron.log
Run Code Online (Sandbox Code Playgroud)

cron/你好-cron

* * * * * root echo "Hello world" >> /var/log/cron.log 2>&1
Run Code Online (Sandbox Code Playgroud)

以上运行良好,其在容器内输出日志,但它们不会流式传输到 docker。

例如 docker logs -f ubuntu-cron返回空结果

如果您登录到容器,则docker exec -it -i ubuntu-cron /bin/bash您有日志。

cat /var/log/cron.log 
Hello world
Hello world
Hello world
Run Code Online (Sandbox Code Playgroud)

现在我想也许我不需要登录到文件?可以将此附加到sttoud,但不确定如何执行此操作。

这看起来很相似... 如何将 cron 作业输出重定向到 stdout

Nee*_*koy 5

我尝试了您的设置,并且以下 Dockerfile 有效:

FROM ubuntu:18.10

RUN apt-get update
RUN apt-get update && apt-get install -y cron

ADD hello-cron /etc/cron.d/hello-cron

# Give execution rights on the cron job
RUN chmod 0755 /etc/cron.d/hello-cron

# Create the log file to be able to run tail
RUN touch /var/log/cron.log

# Symlink the cron to stdout
RUN ln -sf /dev/stdout /var/log/cron.log

# Run the command on container startup
CMD cron && tail -F /var/log/cron.log 2>&1
Run Code Online (Sandbox Code Playgroud)

另请注意,我使用“docker-compose up”而不是 docker 来启动容器。在此特定示例中无关紧要,但如果您的实际解决方案更大,则可能很重要。

编辑:这是我运行 docker-compose up 时的输出:

neekoy@synchronoss:~$ sudo docker-compose up
Starting ubuntu-cron ... done
Attaching to ubuntu-cron
ubuntu-cron | Hello world
ubuntu-cron | Hello world
ubuntu-cron | Hello world
Run Code Online (Sandbox Code Playgroud)

显然在日志中相同:

neekoy@synchronoss:~$ sudo docker logs daf0ff73a640
Hello world
Hello world
Hello world
Hello world
Hello world
Run Code Online (Sandbox Code Playgroud)

我的理解是以上就是目标。


Rob*_*ert 5

由于 docker 层和 inode 中的一些奇怪之处,您必须在 CMD 期间创建文件:

CMD cron && touch /var/log/cron.log && tail -F /var/log/cron.log
Run Code Online (Sandbox Code Playgroud)

这适用于文件和标准输出:

FROM ubuntu:18.10

RUN apt-get update
RUN apt-get update && apt-get install -y cron

ADD hello-cron /etc/cron.d/hello-cron

# Give execution rights on the cron job
RUN chmod 0644 /etc/cron.d/hello-cron

# Create the log file to be able to run tail
# Run the command on container startup
CMD cron && touch /var/log/cron.log && tail -F /var/log/cron.log
Run Code Online (Sandbox Code Playgroud)

解释似乎是这样的:

在原始的 posttail命令中开始“监听”位于图像层中的文件,然后在cron将第一行写入该文件时,docker 将该文件复制到一个新层,即容器层(因为复制的性质-and-write 文件系统,即 docker 的工作方式)。因此,当文件在新层中创建时,它会获得不同的 inode 并tail继续在以前的状态下进行侦听,因此会丢失对“新文件”的每次更新。积分 BMitch