Sobes.tech
Junior

How to view logs in a running container?

sobes.tech AI

Answer from AI

Container logs can be viewed in several ways:

  • docker logs: The standard way to view the container's standard output (stdout) and standard error (stderr).

    // Show all logs of the container
    docker logs <container_id_or_name>
    
    // Show logs from the last 5 minutes
    docker logs --since 5m <container_id_or_name>
    
    // Follow logs in real-time
    docker logs -f <container_id_or_name>
    
  • docker exec with log redirection or reading log files: If the application writes logs to files inside the container, you can run a command inside the container to read them.

    // Run the cat command to read the log file inside the container
    docker exec <container_id_or_name> cat /path/to/your/logfile.log
    
    // Run the tail -f command to follow the log file inside the container
    docker exec <container_id_or_name> tail -f /path/to/your/logfile.log
    
  • Centralized logging systems: In production environments, logs are often collected and aggregated by systems like Elasticsearch, Splunk, Loki, or Graylog. Docker can be configured to send logs directly to these systems via special logging drivers.

    // Example of configuring a logging driver in docker-compose
    services:
      your_service:
        image: your_image
        logging:
          driver: json-file # or syslog, journald, etc.
          options:
            max-size: "10m"
            max-file: "3"
      logging:
        image: elk/elasticsearch # or another logging system image
    

The choice of method depends on where the application inside the container writes its logs and the overall architecture of the monitoring and logging system.