Socket
Socket
Sign inDemoInstall

dockerstats

Package Overview
Dependencies
0
Maintainers
1
Versions
27
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    dockerstats

Simple docker statistics libary


Version published
Weekly downloads
234
increased by172.09%
Maintainers
1
Created
Weekly downloads
 

Readme

Source

dockerstats

Simple Docker info and stats library for node.js

NPM Version NPM Downloads Git Issues Caretaker MIT license

New Version 2

Version 2 just released with several security fixes, improvements and changes.

Breaking Changes Version 2

Be aware, that the new version 2.x is NOT fully backward compatible to version 1.x ...

We had to make several interface changes to keep dockerStats as consistent as possible. We highly recommend to go through the complete list and adapt your own code to be again compatible to the new version 2.

FunctionOldNew (V5)Comments
dockerContainerStats()mem_usage
mem_limit
mem_percent
cpu_percent
cpu_stats
precpu_stats
memory_stats
memUsage
memLimit
memPercent
cpuPercent
cpuStats
precpuStats
memoryStats
pascalCase conformity
dockerContainerProcesses()pid_hostpidHostpascalCase conformity

Quick Start

Collection of a few functions to retrieve detailed docker statistics. With this package you easily can retrieve

  • list of top level/all docker images
  • list of active/all docker containers
  • statistics for a specific container (mem, cpu, network and blockIO stats)
  • information of all processes of a specific active docker container (pids, state, cpu-time, user...)
  • list all docker volumes

Super simple to use with callback functions or promise style.

Installation

$ npm install dockerstats --save

Usage

All functions are implemented as asynchronous functions. Here a small example how to use them:

const dockerstats = require('dockerstats');

// callback style
dockerstats.dockerContainers(function(data) {
	console.log('Docker Containers');
	console.log(data);
})

// promises style
dockerstats.dockerContainers()
	.then(data => console.log(data))
	.catch(error => console.error(error));

// full async / await example (node >= 7.6)
async function dockerContainers() {
  try {
    const data = await dockerstats.dockerContainers();
    console.log(data)
  } catch (e) {
    console.log(e)
  }
}

Core concept

Docker comes with a API to control Docker and retrieve detailes information. So I came up to write this little library to collect some docker statistics. This library is still work in progress. I am sure, there is for sure room for improvement. Tested on several Debian, Raspbian, Ubuntu distributions, OS X (Mavericks, Yosemite, El Captain, Sierra, High Sierra, Mojave).

If you have comments, suggestions & reports, please feel free to contact me!

I also created a full blown system information library (including all docker stats) called systeminformation, also available via github and npm.

Reference

Function Reference and OS Support

FunctionResult objectComments
si.dockerInfo(cb){...}returns general docker info
idDocker ID
containersnumber of containers
containersRunningnumber of running containers
containersPausednumber of paused containers
containersStoppednumber of stopped containers
imagesnumber of images
driverdriver (e.g. 'devicemapper', 'overlay2')
memoryLimithas memory limit
swapLimithas swap limit
kernelMemoryhas kernal memory
cpuCfsPeriodhas CpuCfsPeriod
cpuCfsQuotahas CpuCfsQuota
cpuShareshas CPUShares
cpuSethas CPUShares
ipv4Forwardinghas IPv4Forwarding
bridgeNfIptableshas BridgeNfIptables
bridgeNfIp6tableshas BridgeNfIp6tables
debugDebug on
nfdnamed data networking forwarding daemon
oomKillDisableout-of-memory kill disabled
ngoroutinesnumber NGoroutines
systemTimedocker SystemTime
loggingDriverlogging driver e.g. 'json-file'
cgroupDrivercgroup driver e.g. 'cgroupfs'
nEventsListenernumber NEventsListeners
kernelVersiondocker kernel version
operatingSystemdocker OS e.g. 'Docker for Mac'
osTypeOSType e.g. 'linux'
architecturearchitecture e.g. x86_64
ncpunumber of CPUs
memTotalmemory total
dockerRootDirdocker root directory
httpProxyhttp proxy
httpsProxyhttps proxy
noProxyNoProxy
nameName
labelsarray of labels
experimentalBuildis experimental build
serverVersionserver version
clusterStorecluster store
clusterAdvertisecluster advertise
defaultRuntimedefault runtime e.g. 'runc'
liveRestoreEnabledlive store enabled
isolationisolation
initBinaryinit binary
productLicenseproduct license
si.dockerImages(all, cb)[{...}]returns array of top level/all docker images
[0].idimage ID
[0].containercontainer ID
[0].commentcomment
[0].osOS
[0].architecturearchitecture
[0].parentparent ID
[0].dockerVersiondocker version
[0].sizeimage size
[0].sharedSizeshared size
[0].virtualSizevirtual size
[0].authorauthor
[0].createdcreated date / time
[0].containerConfigcontainer config object
[0].graphDrivergraph driver object
[0].repoDigestsrepo digests array
[0].repoTagsrepo tags array
[0].configconfig object
[0].rootFSroot fs object
si.dockerContainers(all, cb)[{...}]returns array of active/all docker containers
[0].idID of container
[0].namename of container
[0].imagename of image
[0].imageIDID of image
[0].commandcommand
[0].createdcreation time (unix)
[0].startedcreation time (unix)
[0].finishedcreation time (unix)
[0].createdAtcreation date time string
[0].startedAtcreation date time string
[0].finishedAtcreation date time string
[0].statecreated, running, exited
[0].portsarray of ports
[0].mountsarray of mounts
si.dockerContainerStats(ids, cb)[{...}]statistics for specific containers
container IDs: space or comma separated,
pass '*' for all containers
[0].idContainer ID
[0].memUsagememory usage in bytes
[0].memLimitmemory limit (max mem) in bytes
[0].memPercentmemory usage in percent
[0].cpuPercentcpu usage in percent
[0].pidsnumber of processes
[0].netIO.rxreceived bytes via network
[0].netIO.wxsent bytes via network
[0].blockIO.rbytes read from BlockIO
[0].blockIO.wbytes written to BlockIO
[0].cpuStatsdetailed cpu stats
[0].percpuStatsdetailed per cpu stats
[0].memoryStatsdetailed memory stats
[0].networksdetailed network stats per interface
si.dockerContainerProcesses(id, cb)[{...}]array of processes inside a container
[0].pid_hostprocess ID (host)
[0].ppidparent process ID
[0].pgidprocess group ID
[0].usereffective user name
[0].ruserreal user name
[0].groupeffective group name
[0].rgroupreal group name
[0].statprocess state
[0].timeaccumulated CPU time
[0].elapsedelapsed running time
[0].nicenice value
[0].rssresident set size
[0].vszvirtual size in Kbytes
[0].commandcommand and arguments
si.dockerVolumes(cb)[{...}]returns array of all docker volumes
[0].namevolume name
[0].driverdriver
[0].labelslabels object
[0].mountpointmountpoint
[0].optionsoptions
[0].scopescope
[0].createdcreated at
si.dockerAll(cb){...}list of all containers including their stats
and processes in one single array

cb: Asynchronous Function Calls (callback)

Remember: all functions are implemented as asynchronous functions! There are now two ways to consume them:

Callback Style

// assuming you have a container with ID 'ae8a76'

const dockerstats = require('dockerstats');

dockerstats.dockerContainerStats('ae8a76', function(data) {
	console.log('Docker Container Stats:');
	console.log('- ID: ' + data.id);
	console.log('- Mem usage: ' + data.memUsage);
	console.log('- Mem limit: ' + data.memLimit);
	console.log('- Mem usage %: ' + data.memPercent);
	console.log('- CPU usage %: ' + data.cpuPercent);
})

Promises

Promises Style

When omitting callback parameter (cb), then you can use all function in a promise oriented way. All functions are returning a promise, that you can consume:

// assuming you have a container with ID 'ae8a76'

const dockerstats = require('dockerstats');

dockerstats.dockerContainerStats('ae8a76')
  .then(data => {
  	console.log('Docker Container Stats:');
  	console.log('- ID: ' + data.id);
  	console.log('- Mem usage: ' + data.memUsage);
  	console.log('- Mem limit: ' + data.memLimit);
  	console.log('- Mem usage %: ' + data.memPercent);
  	console.log('- CPU usage %: ' + data.cpuPercent);
	})
	.catch(error => console.error(error));

Async / Await

Using async / await (available since node v7.6)

Since node v7.6 you can also use the async / await pattern. The above example would then look like this:

// assuming you have a container with ID 'ae8a76'

const dockerstats = require('dockerstats');

async function dockerContainerData() {
    try {
        const data = await dockerstats.dockerContainerStats('ae8a76');
        console.log('Docker Container Stats:');
        console.log('- ID: ' + data.id);
        console.log('- Mem usage: ' + data.memUsage);
        console.log('- Mem limit: ' + data.memLimit);
        console.log('- Mem usage %: ' + data.memPercent);
        console.log('- CPU usage %: ' + data.cpuPercent);
        console.log('...');
    } catch (e) {
        console.log(e)
    }
}

Version history

VersionDateComment
2.4.22023-06-22fix dockerContainerStats() fix parsing all ‚
2.4.12022-12-18fix util.js after code restructuring
2.4.02022-12-08code restructuring, dockerContainerStats() improved parsing, TS typings update
2.3.02021-05-04dockerImagesInspect(), dockerContainerInspect(), dockerContainerProcesses() security updates
2.2.02021-02-25dockerVolumes added dockerVolumes() - get volume data
2.1.02021-02-24dockerImages added dockerImages() - get image data
2.0.22021-02-23dockerContainerStats fixed param *
2.0.12021-02-15dockerContainerStats fixed ID splitting
2.0.02021-02-14new version 2.0 with security patches, fixes and several updated
1.4.42021-01-02dockerContainerStats fix tx changed to wx as documented
1.4.32020-12-03typescript definitions fix
1.4.22020-10-16dockerContainers() resolved hanging issue
1.4.12019-05-31dockerInfo() changed property naming style
1.4.02019-05-30added typescript definitions, updated docs
1.3.02019-05-29added dockerInfo(), dockerContainers()
added started, finished time, restartCount
1.2.82018-12-03updated package.json (files)
1.2.72018-12-03updated docs
1.2.62018-11-21updated docs
1.2.52018-11-18code cleanup
1.2.42018-11-18bug-fixing - CPU percent calculation (win)
1.2.32018-11-18bug-fixing - CPU percent calculation (linux, win)
1.2.22018-11-18bug-fixing - parsing JSON
1.2.12018-11-18bug-fixing - parsing JSON
1.2.02018-11-06bug-fixing, stabilization, added error handling
1.1.02017-11-06added windows support, dependency version bump
1.0.02016-11-04Initial release

Comments

If you have ideas or comments, please do not hesitate to contact me.

Happy monitoring!

Sincerely,

Sebastian Hildebrandt, +innovations

Credits

Written by Sebastian Hildebrandt sebhildebrandt

Contributers

Linux is a registered trademark of Linus Torvalds. macOS, OS X is a registered trademark of Apple Inc., Windows is a registered trademark of Microsoft Corporation. Node.js is a trademark of Joyent Inc., Intel is a trademark of Intel Corporation. Raspberry Pi is a trademark of the Raspberry Pi Foundation. Debian is a trademark of the Debian Project. Ubuntu is a trademark of Canonical Ltd., Docker is a trademark of Docker, Inc. All other trademarks are the property of their respective owners.

License MIT license

The MIT License (MIT)

Copyright © 2022 Sebastian Hildebrandt, +innovations.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Further details see LICENSE file.

Keywords

FAQs

Last updated on 22 Jun 2023

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc