Dockerized NodeJS container app monitoring its own allocated CPU usage

Viewed 135

I want my containerized NodeJS app to be able to track its own CPU usage but don't find a way of doing it (all I found is to monitor the host cores usage). I don't want to use docker stats inside the container because it would need to run it in privilege mode.

1 Answers

I found the solution using:

  • @adobe/cgroup-metrics

  • CPU count gist (function getCpuLimits()): https://github.com/xiaoxiaojx/get_cpus_length/blob/master/index.js

    const cgroup = require('@adobe/cgroup-metrics');
    const delay = ms => new Promise(_ => setTimeout(_, ms));
    
    // **COPY PASTE HERE THE GIST FUNCTIONS**
    
    const run = async () => {
      const cpu = cgroup.cpu;
      const cpuacct_usage = await cpu.usage();
    
      // Wait 1s
      await delay(1000);
    
      const cpuacct_usage2 = await cpu.usage();
    
      const calculateUsage = await cpu.calculateUsage(cpuacct_usage, cpuacct_usage2);
    
      console.log('calculatedUsage', calculateUsage / getCpuLimits());
    
      return run();
    };
    
    run();
    
Related