Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting script output to docker logs

I have a node.js script running in a node docker container that currently dumps its output to a logfile within the container and STDOUT. Many official docker images allow you to run docker logs container to see the errors of whatever is running in that container.

I see many references that Docker simply captures STD output and this is what docker logs container sees, yet I cannot find any documentation on how to set this up properly from a script running within the container.

Currently my Dockerfile is set up in a way for development with the last line being

ENTRYPOINT [ "npm", "run", "watch"]

which watches my files for changes to run a build script within the container. As such, for development I current use docker exec -it container /bin/sh and execute the script manually.

When I use docker logs container I see the errors from the npm build chain but nothing from my script when run it manually from within the container.

My script uses

process.stdout.write(data)
process.stderr.write(data)

Before I completely redo my Dockerfile for my script, am I correct in thinking that docker logs redirects STDOUT and STDERR from a process with PID 1 but not any other processes running on different PIDs?

And if I want to capture my script output using docker logs it is simply a case of changing the ENTRYPOINT so it runs my script directly?

ENTRYPOINT [ "node", "myscript" ]
like image 520
myol Avatar asked Jul 10 '26 02:07

myol


1 Answers

Your assumption is close - Docker logs output from whichever process was used to launch the container. That is indeed PID 1, but some containers will use a "fake" init process so the main process doesn't run as such (like Tini), which is also the case if you use docker run --init.

In your case, if you docker exec into a container and run commands, the output isn't going to be logged because it's being sent to your shell session. If you change your ENTRYPOINT to run your script directly, then Docker will see the output of your script.

Alternatively, if you want to send output to the container logs collector without changing the container entrypoint, you can send output to PID 1's stdio streams within the container. For example, to send output to PID 1's stdout:

$ docker exec -it $RUNNING_CONTAINER bash
container$ echo test >> /proc/1/fd/1          # fd/1 for stdout
like image 158
hexacyanide Avatar answered Jul 11 '26 16:07

hexacyanide



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!