I have a debian slim docker container running an ASP.Net Core 3.1 application. (mcr.microsoft.com/dotnet/aspnet:3.1.16-buster-slim)
I would like to be able to get the total memory used by the container that it is running the application.
NOTE: I am not looking for the memory used by the application/process. That is easily done with Process.GetCurrentProcess().WorkingSet64
.
How can I get the memory usage for the container from the application using ASP.Net Core?
For bonus points, I would love to know CPU % utilization and available memory (again, both for the linux container, not the runing processing.
2
Answers
to get the memory usage for the container, You can use
docker stats
command as below:First thing first, you need access to the Docker Engine from within the container. Just like with vanilla VM’s, you can’t inspect the host system unless you have some allowed way to get that data (a VM might know it’s a VM, but it shouldn’t be able to know what other VMs are on the host system without permission).
The easiest method to get access is with the Docker Socket. You can also use the Docker REST API.
If you’re able to, it might be a safe play to add a "read only" flag to the end of the volume. That way your software can’t go rogue as much and start deleting things willy-nilly.
Once you have the socket setup, you can use a library like Microsoft’s own Docker.DotNet to communicate over that socket.
You can inspect any aspect of the Docker Engine, such as the "stats" of each/any container.
I do want to echo nyctef‘s comment though. A container is different than a VM. A VM runs an entire OS and your software. A container is just a single (usually) process, so in most cases the memory used by your container and the memory used by your software process should be nearly identical (with the Docker overhead).