SangminKim
SangminKim

Reputation: 9146

Why does redirecting container stdout to a file not work?

I set an simple environment for testing.

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

Run the test container

$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...

Check test.log inside the container

$ docker exec -it simple_test bash
$ cd /
$ ls 
# No file named `test.log`

docker seems to just ignore redirection. Is it normal and why? or I did wrong way something?

Edit

Thank you @Sebastian for your answer. it works redirecting stdout to a file. However, one more question.

The docs you refer also is saying the below.

If you use the shell form of the CMD, then the will execute in /bin/sh -c:

As my understanding of that, command: /test.sh > /test.log is equivalent with command: ["sh", "-c", "/test.sh > /test.log"].

However, when I did command: /test.sh > /test.log, it didn't redirect as well.

Why does command: ["sh", "-c", "/test.sh > /test.log"] work but command: /test.sh > /test.log.

Do I misunderstand?

Upvotes: 0

Views: 3974

Answers (2)

manoj
manoj

Reputation: 1

i think you are doing something wrong with syntax , "command" parameter works with compose and also did same thing as CMD. try to use command: sh -c '/test.sh > /tmp/test.log' in your compose file. it works fine.

Upvotes: 0

Sebastian
Sebastian

Reputation: 17443

You need to make sure your command is executed in a shell. Try to use:

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

You specified the command/ entrypoint as JSON which is called exec form

The exec form does not invoke a command shell. This means that normal shell processing does not happen.

Docker docs

Upvotes: 2

Related Questions