为什么将容器标准输出重定向到文件不起作用?

时间:2018-01-08 08:59:42

标签: docker docker-compose io-redirection

我设置了一个简单的测试环境。

Dockerfile

FROM ubuntu:16.04
COPY test.sh /
ENTRYPOINT /test.sh

test.sh

#!/bin/bash
while true; do
    echo "test..."
    sleep 5
done

搬运工-compose.yml

version: '3.4'

services:

    test:
        image: asleea/simple_test
        entrypoint: ["/test.sh", ">", "test.log"]
        # command: [">", "/test.log"]
        container_name: simple_test

运行测试容器

$docker-compose up
WARNING: The Docker Engine you're using is running in swarm mode.

Compose does not use swarm mode to deploy services to multiple nodes in a swarm. All containers will be scheduled on the current node.

To deploy your application across the swarm, use `docker stack deploy`.

Starting simple_test ... 
Starting simple_test ... done
Attaching to simple_test
simple_test | test...
simple_test | test...
  • 它仍然在那里打印stdout

检查容器内的test.log

$ docker exec -it simple_test bash
$ cd /
$ ls 
# No file named `test.log`
  • test.log用于重定向不存在。

docker似乎只是忽略了重定向。这是正常的,为什么?或者我做错了什么?

修改

谢谢@Sebastian的回答。它可以将stdout重定向到文件。 但是,还有一个问题。

您提到的docs也在说下面的内容。

  

如果您使用CMD的shell形式,那么将执行   在/ bin / sh -c:

根据我的理解,command: /test.sh > /test.logcommand: ["sh", "-c", "/test.sh > /test.log"]相同。

但是,当我command: /test.sh > /test.log时,它也没有重定向。

为什么command: ["sh", "-c", "/test.sh > /test.log"]可以工作,但command: /test.sh > /test.log

我误解了吗?

2 个答案:

答案 0 :(得分:2)

您需要确保您的命令在shell中执行。尝试使用:

CMD [ "sh", "-c", "/test.sh", ">", "test.log" ]

您将命令/入口点指定为JSON,称为 exec表单

  

exec表单不会调用命令shell。   这意味着不会发生正常的shell处理。

Docker docs

答案 1 :(得分:0)

我认为你在做错了语法,"命令"参数与compose一起工作,也和CMD一样。尝试使用命令:sh -c' /test.sh>你的撰写文件中的/tmp/test.log' 。它工作正常。