Docker 为什么将容器stdout重定向到文件不起作用?

Docker 为什么将容器stdout重定向到文件不起作用?,docker,docker-compose,io-redirection,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 docker compose.yml version: '3.4' services: test: image: asleea/simple_test

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

Dockerfile

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

test.sh

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

docker 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...
$ docker exec -it simple_test bash
$ cd /
$ ls 
# No file named `test.log`
  • 它仍在那里打印
    stdout

检查容器内的
test.log

$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...
$ docker exec -it simple_test bash
$ cd /
$ ls 
# No file named `test.log`
  • 重定向的
    test.log
    不存在
docker
似乎只是忽略了重定向。这正常吗?为什么?还是我做错了什么

编辑 谢谢你@Sebastian的回答。它可以将标准输出重定向到文件。 然而,还有一个问题

你提到的那个人也在说下面的话

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

据我所知,
命令:/test.sh>/test.log
等同于
命令:[“sh”、“-c”、“/test.sh>/test.log”]

但是,当我执行
命令:/test.sh>/test.log
时,它也没有重定向

为什么
命令:[“sh”、“-c”、“/test.sh>/test.log”]
起作用,但
命令:/test.sh>/test.log


我误解了吗?

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

CMD [ "sh", "-c", "/test.sh", ">", "test.log" ]
您将命令/入口点指定为JSON,称为exec form

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


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

CMD [ "sh", "-c", "/test.sh", ">", "test.log" ]
您将命令/入口点指定为JSON,称为exec form

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


我认为您在语法上犯了一些错误,“command”参数与compose一起工作,并且与CMD做了相同的事情。尝试在您的撰写文件中使用命令:sh-c'/test.sh>/tmp/test.log'。它很好用

我认为您的语法有问题,“command”参数与compose一起工作,并且与CMD做了相同的事情。尝试在您的撰写文件中使用命令:sh-c'/test.sh>/tmp/test.log'。它很好用

谢谢你!。它可以工作,但你能在我编辑的帖子上再回答一个问题吗?@SangminKim在docker compose中,你似乎必须添加
sh-c
才能工作。你有没有试过普通码头工人的方案?谢谢!。它可以工作,但你能在我编辑的帖子上再回答一个问题吗?@SangminKim在docker compose中,你似乎必须添加
sh-c
才能工作。你有没有试过用普通的docker做你的场景?