Mandeep Singh
Mandeep Singh

Reputation: 8234

How to capture logs of a command run through `docker-compose exec -d` in background?

Consider a docker-compose.yml file like this:

version: '3'

services:
  test:
    image: ubuntu:18.04
    tty: true

I can bring up the services in background by running docker-compose up -d

Now I can run commands on this container by using docker-compose exec

For example:

docker-compose exec test ls -lrt | head -3

When I run the above command, I get the output on my terminal

total 64
drwxr-xr-x   8 root root 4096 May 23  2017 lib
drwxr-xr-x   2 root root 4096 Apr 24  2018 home

Now what I want is to be able to run the above command in background which I can do with

docker-compose exec -d test ls -lrt | head -3

The command will run in the background which is fine. But how can I access the output of the above command?

Upvotes: 8

Views: 1213

Answers (2)

sparrowt
sparrowt

Reputation: 3008

You can redirect the output of your COMMAND by doing exec as follows:

docker compose exec -d <servicename> sh -c "COMMAND > /proc/1/fd/1"

so that the logs will be available via docker-compose logs (see also this answer) just like logs that came from the original container entrypoint.

I realise the OP doesn't want this, but if you do want the logs to be shown in the console from which you ran the exec then instead then do this: (even without -d the > will swallow them)

docker compose exec <servicename> sh -c "COMMAND | tee /proc/1/fd/1"

Upvotes: 0

Pierre B.
Pierre B.

Reputation: 12953

You can redirect output in a file inside your container and output the content of this file afterward, such as:

# execute command and redirect to output.log in container
docker-compose exec -d test sh -c 'ls -lrt | head -3 > /tmp/output.log'

# retrieve output content
docker-compose exec test cat /tmp/output.log

Upvotes: 2

Related Questions