php - 使用 PHP 创建和删除文件后 Docker 不释放内存

标签 php docker memory debian kubernetes

我有一个 PHP 守护进程脚本下载远程图像并在上传到对象存储之前将它们临时存储在本地。

PHP 内部内存使用量保持稳定,但 Docker/Kubernetes 报告的内存使用量不断增加。

我不确定这是否与 PHP、Docker 或预期的 Linux 行为有关。

重现问题的示例:

Docker 镜像:php:7.2.2-apache

<?php
for ($i = 0; $i < 100000; $i++) {
    $fp = fopen('/tmp/' . $i, 'w+');
    fclose($fp);

    unlink('/tmp/' . $i);

    unset($fp);
}

调用 free -m在执行上述脚本之前在容器内:
          total        used        free      shared  buff/cache   available
Mem:           3929        2276         139          38        1513        1311
Swap:          1023         167         856

并在执行脚本后:
          total        used        free      shared  buff/cache   available
Mem:           3929        2277         155          38        1496        1310
Swap:          1023         167         856

显然内存被释放但调用 docker stats php-apache从主机指示其他内容:
CONTAINER ID        NAME                CPU %               MEM USAGE / LIMIT     MEM %               NET I/O             BLOCK I/O           PIDS
ccc19719078f        php-apache          0.00%               222.1MiB / 3.837GiB   5.65%               1.21kB / 0B         1.02MB / 4.1kB      7
docker stats php-apache 报告的初始内存使用情况是 16.04MiB。

解释是什么?如何释放内存?

在具有资源限制的 Kubernetes 集群中运行此容器会导致 pod 失败并反复重启。

最佳答案

是的,已经报告了类似的问题 here .

Here's the answer Coolljt0725 的贡献者之一,回答为什么 RES栏目top输出显示与 docker stats 不同的内容(我只是按原样引用他的话):

If I understand correctly, the memory usage in docker stats is exactly read from containers's memory cgroup, you can see the value is the same with 490270720 which you read from cat /sys/fs/cgroup/memory/docker/665e99f8b760c0300f10d3d9b35b1a5e5fdcf1b7e4a0e27c1b6ff100981d9a69/memory.usage_in_bytes, and the limit is also the memory cgroup limit which is set by -m when you create container. The statistics of RES and memory cgroup are different, the RES does not take caches into account, but the memory cgroup does, that's why MEM USAGE in docker stats is much more than RES in top



用户建议 here实际上可能会帮助您查看真实的内存消耗:

Try set the param of docker run --memory,then check your /sys/fs/cgroup/memory/docker/<container_id>/memory.usage_in_bytes It should be right.


--memory-m描述 here :

-m, --memory="" - Memory limit (format: <number>[<unit>]). Number is a positive integer. Unit can be one of b, k, m, or g. Minimum is 4M.



现在如何避免不必要的内存消耗。正如您发布的那样,在 PHP 中取消链接文件不需要立即删除内存缓存。相反,在特权模式下运行 Docker 容器(带有 --privileged 标志),然后可以调用 echo 3 > /proc/sys/vm/drop_cachessync && sysctl -w vm.drop_caches=3定期清除内存pagecache。

作为奖励,使用 fopen('php://temp', 'w+')并将文件临时存储在内存中可以避免整个问题。

关于php - 使用 PHP 创建和删除文件后 Docker 不释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49159036/

相关文章:

php - 亚马逊 mws api 类 'MarketplaceWebService_Client' 未找到错误

docker - 运行docker容器时如何自动启动服务?

mysql - 无法将tomcat容器连接到kubernetes中的mysql数据库容器?

c - 给定字符串分配不同内存的原因是什么?

Javascript 游戏信息到 PHP

php - MySQL 中的浮点值本身

c - 内存如何确定变量的数据类型?

java - 大字节数组使用的堆比预期多

php - CSS 页脚样式

docker - 在集群/Docker-Swarm中映射Docker卷