内存泄漏在 Docker 容器中在容器被终止后会消失吗?

huangapple go评论63阅读模式
英文:

memory leak in docker container will disappear after the container is been killed?

问题

我正在编写和测试一个在Docker容器中的C++程序。我没有指定容器的最大内存大小。

docker run -it xxx:latest /bin/bash

C++程序有时会导致内存泄漏,例如没有释放分配的堆内存。

所以我很好奇,当我杀死容器时,内存泄漏是否会在主机Linux上消失?

或者容器中的程序引起的这个内存泄漏是否仍然存在于主机上?

英文:

I am writing and testing a cpp program in a docker container. And I did not designate the max memory size for the container.

docker run -it xxx:latest /bin/bash

And cpp program will sometimes cause memory leak such as not free the allocated heap memory.

So I am curious that if the memory leak will disappear in the host linux when I kill the container?

Or this memory leak caused by the program in the container still exists in the host?

答案1

得分: 1

一个Docker容器是一个围绕单个进程的封装。终止容器也会终止该进程;反之,如果进程自行退出,也会导致容器退出。

终止一个进程会释放该进程使用的所有内存。因此,如果你有一个C++程序,它调用了new但没有相应的delete,它会泄露内存,但终止该进程将收回所有该进程的内存,甚至是应用程序已经失去追踪的空间。如果进程在容器中运行,仍然适用相同的规则。

这也适用于其他类似内存泄漏的行为,以及其他编程语言;例如,向列表追加大量值然后忽略它们,使它们仍然“被不必要地使用”。一些其他的操作系统资源,如文件描述符,也会通过这种方式清理,但有些不会。特别是,如果你fork(2)了一个子进程,你必须自己清理它。同样,如果你可以访问Docker API,你必须清理掉你自己启动的任何相关容器。

英文:

A Docker container is a wrapper around a single process. Killing the container also kills that process; conversely, if the process exits on its own, that causes the container to exit too.

Ending a process will release all of the memory that process used. So, if you have a C++ program, and it calls new without a corresponding delete, it will leak memory, but ending the process will reclaim all of the process's memory, even space the application has lost track of. This same rule still applies if the process is running in a container.

This also applies to other leak-like behavior and in other languages; for example, appending a very large number of values to a list and then ignoring them, so they're still "in use" unnecessarily. Some other OS resources like file descriptors are cleaned up this way, but some are not. In particular, if you fork(2) a subprocess, you must clean up after it yourself. Similarly, if you have access to the Docker API, you must clean up any related containers you spawn yourself.

huangapple
  • 本文由 发表于 2023年1月9日 14:13:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75053723.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定