关于docker:容器的swap内存

4次阅读

共计 1537 个字符,预计需要花费 4 分钟才能阅读完成。

Linux 上 swap 内存对应一块磁盘分区,当内存缓和时,能够把内存中的数据写入到 swap 分区;当须要读写这部分数据时,又能够将其从 swap 分区读入内存。

一. 容器 swap 内存的弊病

容器应用 swap 内存,会导致 Memory CGroup 对容器内存的限度生效。

比方,在一个开启 swap 的节点上,启动一个容器:

  • 容器的 Memory Cgroup 限度 =100MB;
  • 容器中的过程继续申请内存,共申请 1GB 内存;

容器的内存尽管限度在 100MB,然而因为应用了 swap,导致容器申请 1GB 内存胜利(应用 swap 换入换出),也不会被 OOM Kill。

也就是说,在应用 Swap 的场景下,Memory CGroup 对容器的内存限度 limit 就生效了。

二. 容器敞开 swap 分区(举荐)

启动容器时,减少启动参数 –memory-swappiness=0,即可禁止容器应用 swap;

–memory-swappiness details
A value of 0 turns off anonymous page swapping.
A value of 100 sets all anonymous pages as swappable.
By default, if you do not set –memory-swappiness, the value is inherited from the host machine.

同时,配置 –memory 的值 与 –memory-swap 的值 相等,也能够阻止容器应用 swap:

Prevent a container from using swap
If –memory and –memory-swap are set to the same value, this prevents containers from using any swap.
This is because –memory-swap is the amount of combined memory and swap that can be used, while –memory is only the amount of physical memory that can be used.

三. 容器应用 swap 分区

某些程序,可能须要应用 Swap 空间,能力避免因为偶然的内存忽然减少,而被 OOM Kill 杀死。

那么,容器过程的内存有哪些组成部分,在内存缓和时,优先选择哪局部写入 swap 分区呢?

1. 容器过程内存

容器过程内存次要有 2 局部:

  • RSS: Resident Set Size

    • RSS 中的内存,次要是 malloc()申请失去的内存,也称为匿名内存(Anonymous memory);
    • 当 Swap 开启后,在内存缓和时,能够将 RSS 的内存写入 swap 空间;
  • Page Cache:

    • 在有磁盘文件拜访的时候,Linux 会尽量把零碎的闲暇内存用作 Page Cache 来提供文件的读写性能;
    • 一旦内存不够,就会产生内存回收,回收 Page Cache;

那么,当内存缓和时,Linux 零碎是如何抉择 开释 Page Cahce 还是 将匿名内存写入 Swap

这由容器的 swappiness 参数决定。

2. 容器的 swappiness 参数

Memory CGroup 下,每个容器都有 memory.swappiness 参数:

# cat memory.swappiness
60

该参数的值,决定了 开释 Page Cahce将匿名内存写入 Swap的优先级:

  • 默认 =60:

    • 优先选择 开释 Page Cahce
  • 当 swappiness=100 时:

    • 开释 Page Cahce将匿名内存写入 Swap 有雷同的优先级,等比例开释;
  • 当 swappiness= 0 时:

    • 禁止应用 swap;

参考

1.docker swap 参数:https://docs.docker.com/config/containers/resource_constraint…

正文完
 0