Writing log files in NodeJS Docker container

Viewed 7199

I want to write log files to the host file system, so it is persisted, even if the Docker container dies.

Do I need to mount a volume in my Docker yaml?

VOLUME /var/log/myApp

Then do I just reference the mount like this?

var stream = fs.createWriteStream(`/var/log/myApp/myLog.log`);
stream.write('Hello World!');

Then outside of my container, I can go to the /var/log/myApp/ directory and see my logs.

I am trying to find an example of this, but haven't seen anything.

1 Answers

When you're setting up your container, you just use the -v argument:

-v ./path/to/local/directory:/var/log/myApp

The first path is where the volume is available on the host system (the period at the beginning means it's relative to where you're running the docker command). The path on the right hand side is where it's available in the container.

Once more, in docker-compose:

    volumes:
        - "./path/to/local/directory:/var/log/myApp"

And yes, this will allow the data stored in the volume to be persistent.

Related