Day 20: Mastering Docker Logs

Adrian Rubico

|

Jan 10, 2025

09:21 PM GMT+8

Containerized applications rely on logs for diagnosing and troubleshooting issues. Docker easy access to log files, enabling developers to understand container behavior and pinpoint errors. In this blog, we will explore how Docker logs are utilized, delve into viewing them in foreground and background modes, and address common problems such as database initialization errors.

Tasks

Check Logs When Running a Container in the Background

Viewing logs in detached mode is crucial for monitoring container behavior without interrupting its execution. This is helpful for tracking errors or confirming expected operations.

To run a container in the background (detached mode) and check its logs:

  1. Start the Nginx container in detached mode:
docker run -d -p 8080:80 --name my-nginx nginx:latest

  1. View the container's logs:
docker logs my-nginx

Check Logs When Running a Container in the Foreground

Running a container in the foreground provides real-time log visibility, which is invaluable for troubleshooting issues during custom image builds or for obtaining immediate feedback on application startup.

To run a container in the foreground (interactive mode) and view logs directly:

  1. Run the Nginx container (Press Ctrl+C to send the SIGINT signal and stop the process):
docker run -P --name my-nginx nginx:latest

Run a MySQL Database and Check Logs for Errors

  1. Start a MySQL container in detached mode:
docker run -d -P --name mysql mysql:8.0

  1. Verify the container's status:
docker ps
docker ps -a

  1. Check the logs for errors:
docker logs mysql

  1. Fix the error issue, specify the root password using the -e flag:
docker run -d -P --name mysql -e MYSQL_ROOT_PASSWORD=mysqlpwd mysql:8.0

  1. Verify the container is running properly:
docker ps

Conclusion

It has been discussed in this blog how to monitor container activity in both foreground and background modes with Docker logs. By setting environment variables, we were able to resolve a common MySQL container initialization error.

In the next blog, we will dive deeper into Docker Volumes, exploring data persistence strategies for containerized applications.

Discussion