How to redirect Docker logs to file?
To redirect Docker container logs to a file, you can use the
--log-opt options when running the container. Docker provides several logging drivers, and you can choose one that suits your needs. The most commonly used logging drivers are
json-file (the default),
journald. Here's how you can redirect Docker logs to a file using the
json-file logging driver:
1. Create a Docker Container with Redirected Logs
This will run the container with the
json-file logging driver and redirect the container's logs to files. The logs will be stored in the
/var/lib/docker/containers/container_id/container_id-json.log file on the host, where
container_id is the unique ID of your container.
docker run -d --name your_container_name \
--log-opt max-size=10m \
--log-opt max-file=3 \
d: Run the container in detached mode (in the background).
-name your_container_name: Give a name to the container.
-log-driver=json-file: Use the
json-filelogging driver to redirect logs to files.
-log-opt max-size=10m: Set the maximum size of each log file to 10 megabytes (adjust as needed).
-log-opt max-file=3: Set the maximum number of log files to rotate before removing old logs (adjust as needed).
your_image_name: Replace this with the name of the Docker image you want to run in the container.
2. View the Logs
To view the logs of the running container, you can use the
docker logs command:
docker logs your_container_name
This will display the logs on the console.
If you want to save the logs to a file on your host system, you can use output redirection:
docker logs your_container_name > container_logs.txt
This will save the container logs to the
container_logs.txt file on your host system.
Remember to adjust the logging driver and options according to your requirements. Other logging drivers, such as
journald, are also available and might be more suitable for specific use cases. The
json-file driver is commonly used for redirecting logs to files when you want to keep the logs outside of Docker's default logging mechanism.
To learn more about logging, visit Better Stack Community.
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.Write for us
Build on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our firstname.lastname@example.org
or submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github