Docker Fetching Logs from Containers

In this guide, we will see how to fetch the logs from a Docker container, allowing you to obtain insights into container activity. To demonstrate this topic, we will run and retrieve logs from a Dockerized MySQL container.

Step 1: Setup 

Ensure Docker is installed and running on your machine. If not, you can follow the official documentation to set it up. 

Step 2: Running a Container 

Before we extract logs, ensure that a MySQL container is actively running. Launch a MySQL instance with:

docker run --name mysql-container -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:latest

This will instantiate a MySQL container named mysql-container, with the root password set as my-secret-pw.

Step 3: Fetching Logs from the MySQL Container 

To retrieve logs from an active container, apply the following command:

docker logs mysql-container

Upon specifying the container's name (mysql-container), the logs will populate your terminal:

2023-08-15 05:48:01+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.23-1debian10 started.
2023-08-15 05:48:01+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2023-08-15 05:48:01+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.23-1debian10 started.
2023-08-15 05:48:01+00:00 [Note] [Entrypoint]: Initializing database files
2023-08-15 05:48:01+00:00 [Warning] [Entrypoint]: Database files initialized
2023-08-15 05:48:01+00:00 [Note] [Entrypoint]: Starting temporary server
2023-08-15 05:48:03+00:00 [Note] [Server]: Temporary server started.
2023-08-15 05:48:03+00:00 [Note] [Server]: Setting root password.
2023-08-15 05:48:05+00:00 [Note] [Server]: Temporary server stopped.
2023-08-15 05:48:05+00:00 [Note] [Entrypoint]: MySQL init process done. Ready for start up.

Step 4: Diving Deeper into Logging Options 

1. Real-time Logging with Follow Option (-f): 

For continuous log monitoring (invaluable for live debugging), utilize the -f or --follow switch:

docker logs -f mysql-container
2. Showcasing the Last n Lines: 

If your focus is solely on recent logs, employ the --tail option:

docker logs --tail 100 mysql-container

This manifests the last 100 log lines.

3. Incorporating Timestamps: 

Embed timestamps within the log output to refine your troubleshooting:

docker logs --timestamps mysql-container

Conclusion 

In this guide, we have seen how to set up a MySQL container and how to use the docker logs command to retrieve MySQL container logs.

Related Container Management Guides

Comments