Lesson 28: Basic Monitoring and Logging (docker logs)
In a containerized environment, applications should write their logs to standard output (stdout) and standard error (stderr). Docker captures these streams, making logging centralized and easy to manage.
1. Viewing Container Logs
The docker logs command retrieves the logs captured by the Docker daemon for a specific container.
Start a temporary Nginx container for testing:
bash docker run -d --name test_log nginx
View the logs of the running container:
bash docker logs test_log
2. Following Logs in Real-Time
Use the -f (follow) flag to stream new logs as they are generated, similar to tail -f.
bash docker logs -f test_log
If you make a request to the Nginx server (e.g., access http://localhost:80 if mapped), you will see the access logs streamed immediately.
3. Advanced Logging Options
-
Timestamping: Use the
-tflag to add timestamps to the log lines. bash docker logs -t test_log -
Filtering: Use the
--sinceflag to view logs starting from a specific time. bash docker logs --since "5m" test_log # Logs from the last 5 minutes
4. Resource Usage Monitoring (docker stats)
To view real-time statistics (CPU usage, Memory usage, Network I/O) for all running containers, use docker stats.
bash docker stats
This provides a live dashboard view, helping you identify containers that are consuming excessive resources.