Read a bounded event window
The client wrapssystemEvents() in an EventStream. Its callback receives
one EventMessage model per event. Query timestamps are strings in this
API line, even when expressed as Unix seconds.
until only when you intend to keep listening. Filtering limits which
events arrive; it does not impose a timeout. Docker event history is bounded,
so this is not a durable audit log. Persist relevant events yourself, handle
reconnects and reconcile current state through inspect/list calls rather than
assuming no events were lost. Keep slow work out of the synchronous callback.
Read one stats sample
containerStats() streams by default and returns a StatsStream (see
continuous stats). Set stream => false to get one sample
instead:
ContainerStatsResponse models. With an
earlier API line, they are decoded stdClass objects: read
$stats->memory_stats->usage instead. Use null checks: cgroup versions and
daemon configuration affect which fields are present. one-shot => true can
reduce waiting for a single sample, but must be combined with stream => false
and may not provide the previous CPU sample needed for a percentage calculation.
Raw memory usage is not necessarily the cache-adjusted value shown by the
Docker CLI. Likewise, CPU percentage needs current/previous CPU counters,
system counter deltas and a CPU count; it is not one field which can simply
be divided by a constant. Check zero/missing counters and the daemon’s cgroup
version before calculating percentages.
Continuous stats
With the defaultstream => true, containerStats() returns a StatsStream.
Docker sends a sample about once a second until the container stops, so call
stop() once you have what you need. Its callback receives each sample in the
same form as stream => false:
stop() closes the response body, and wait() returns after the current
sample’s callbacks have run. Each sample’s precpu_stats holds the previous
reading, so a CPU percentage can be calculated from the second sample onwards.
With an API line before 1.48, type the callback parameter as stdClass.
Live samples need a transport that reads
incrementally, such as the bundled socket client. Guzzle’s cURL handler
buffers the whole response; see HTTP clients. Keep the reader
in a worker rather than an ordinary web request, and see
stream lifetime and cancellation.