How do I run psutil inside a docker container?

I am trying to monitor the processor and memory of my docker container from my python application. I am planning on using psutil for this job. I've read on other forums about what /proc

can be changed in psutil.

import psutil
psutil.PROCFS_PATH = 'proc/self'
psutil.cpu_percent()

      

This gives me the following error:

 File "app.py", line 22, in <module>
 web-vote-app_1  |     r = psutil.cpu_percent()
 web-vote-app_1  |   File "/usr/local/lib/python2.7/site-packages/psutil       /__init__.py", line 1773, in cpu_percent
 web-vote-app_1  |     _last_cpu_times = cpu_times()
 web-vote-app_1  |   File "/usr/local/lib/python2.7/site-packages/psutil/__init__.py", line 1645, in cpu_times
 web-vote-app_1  |     return _psplatform.cpu_times() 
 web-vote-app_1  |   File "/usr/local/lib/python2.7/site-packages/psutil/_pslinux.py", line 544, in cpu_times
 web-vote-app_1  |     fields = [float(x) / CLOCK_TICKS for x in fields]
 web-vote-app_1  | ValueError: could not convert string to float: (python)
 web-result_1    |  * Running on http://0.0.0.0:5002/ (Press CTRL+C to quit)
 swarmmicroservicedemov1_web-vote-app_1 exited with code 1

      

Can anyone tell me if it is possible to get the same information about the container instead of the host if that is the case. as? Thanks to

+3


source to share


1 answer


Why are you changing the default path /proc/

?

It works:

import psutil
psutil.cpu_percent(interval=1)

      

Every container has already installed it correctly / proc. Therefore, psutil can work without additional connectivity.




Edit: see work

Dockerfile:

FROM python:2

RUN pip install psutil

CMD sh -c 'while true; do python -c "import psutil; print psutil.cpu_percent()"; sleep 0.5; done'

      

Build and run:

docker build . -t psutil-test && docker run -it psutil-test
Sending build context to Docker daemon 2.048 kB
Step 1/3 : FROM python:2
 ---> 2e9467da064d
Step 2/3 : RUN pip install psutil
 ---> Using cache
 ---> bdb07a51b12b
Step 3/3 : CMD sh -c 'while true; do python -c "import psutil; print psutil.cpu_percent()"; sleep 0.5; done'
 ---> Using cache
 ---> 028f88f8844c
Successfully built 028f88f8844c
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0

      

+7


source







All Articles