redirect log files created in a docker container to stdout / stderr

Viewed 21151

I have the following Dockerfile:

FROM ubuntu:16.04
RUN apt-get update
VOLUME ["/LOGS"]
COPY ./testServer .
ENTRYPOINT ./testServer 8600

"testServer" has log files that are being written to. They are located in the directory "LOGS". Each time "testServer" is started, a new log is created. What I wanted to do was to "tail" the latest log file in the directory to stdout / stderr.

I tried adding:

CMD ["/bin/sh", "-c", "tail $( ls -Art /LOGS | tail -n 1 ) > out_server.log 2>&1"]

to the Dockerfile (and rebuilt the image thereafter) but it did not work.

How can this be done?

TIA

4 Answers

Instead you using tail, you can symlink the log file to the container process's stdout. To do so, you need to wrap your executable in a separate script so it gets launched as a process separate from the container's main process.

Script to execute:

#!/bin/bash

# The application log will be redirected to the main docker container process's stdout, so # that it will show up in the container logs
touch /my/app/application.log
ln -sf /proc/1/fd/1 /my/app/application.log

# Execute my app
./testServer 8600

And in the docker file just copy and execute the script

COPY start_server.sh /the/above/script/start_server.sh
CMD ["/bin/bash", "/the/above/script/start_server.sh"]

I found following useful.

#forward request and error logs to docker log collector
RUN ln -sf /dev/stdout /var/log/nginx/access.log \
    && ln -sf /dev/stderr /var/log/nginx/error.log

As a result of above lines, content written to access.log and error.log will be written to stdout and stderr respectively.

Source

Related