Writing logs in a container

Notes

Logging PID1

The official nginx image creates a symbolic link from /var/log/nginx/access.log to /dev/stdout, and creates another symbolic link from /var/log/nginx/error.log to /dev/stderr, overwriting the log files and causing logs to be sent to the relevant special device instead. See the Dockerfile.

Example

# 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

Logging processes other than PID1

To log processes other than PID1 you need to send data to /proc/1/fd/1 for stdout and /proc/1/fd/2 for stderr.

Example

# set a crontab renewal of certs
SLEEPTIME=$(awk 'BEGIN{srand(); print int(rand()*(3600+1))}'); \
    echo "0 0,12 * * * root sleep $SLEEPTIME && certbot renew -q && echo 'cerbot renewed' >> /proc/1/fd/1" | crontab -