dockerdocker-composecontainersdockerfiledocker-container

Docker container save logs on the host directory


I have a question similar to this one. When run my docker-compose.yml file, I automatically create a docker image and as specified in my dockerfile, I run certain apps. These apps produce some logs, but these logs are written inside the docker container, in /home/logs/ folder.

How can I indicate that these logs be writted outside the container, on my /path/on/host address? Simply because if the container was failed, I need to see the logs and not lose them!

This is my docker-compose.yml:

version: '3'
services:
  myapp:
    build: .
    image: myapp
    ports:
      - "9001:9001"

and here is my dockerfile:

FROM java:latest
COPY myapp-1.0.jar /home
CMD java -jar /home/myapp-1.0.jar

And I simply run it on production machine with docker-compose up -d.

(BTW, I'm new to dockers. Are all of my steps correct? Am I missing anything?! I see all is fine and myapp is running though!)


Solution

  • All you need is a docker volume in order to persist the log files. So in the same directory as your docker-compose.yml create a logs directory, then define a volume mount. When defining a mount remember the syntax is <host_machine_directy>:<container_directory>.

    Give the following volume a try and let me know what you get back.

    version: '3'
    services:
      myapp:
        build: .
        image: myapp
        ports:
          - "9001:9001"
        volumes:
          - ./logs:/home/logs
    

    Also worth noting that persistence goes both ways with this approach. Any changes made to the files from within the container are reflected back onto the host. Any changes from the host, are also reflected inside the container.