限制 Docker 容器的内存与 CPU 资源

默认情况下,容器没有资源限制,可以使用宿主机内核调度器允许它使用的资源。Docker 通过 docker run 的运行时配置参数,控制容器可使用的内存或 CPU。本页说明何时应设置这些限制,以及设置后可能产生的影响。

许多功能需要内核支持相应的 Linux 能力。可以用 docker info 检查支持情况。如果内核禁用了某项能力,输出结尾可能出现这样的警告:

WARNING: No swap limit support

如何启用相关能力,请查阅操作系统文档。更多信息见 Docker Engine 故障排查指南。

内存

理解内存耗尽的风险

不要让正在运行的容器消耗过多宿主机内存。在 Linux 宿主机上,如果内核发现剩余内存不足以执行重要系统功能,就会发生内存耗尽错误,并开始终止进程来释放内存。任何进程都可能被终止,包括 Docker 和其他重要应用。如果错误地终止了关键进程,整个系统可能停止正常工作。

Docker 会调整 Docker 守护进程的 OOM 优先级,使其相较其他系统进程更不容易被终止,以缓解风险。容器的 OOM 优先级不会被调整,因此单个容器比 Docker 守护进程或其他系统进程更可能被终止。不要通过给守护进程或容器设置极低的负数 --oom-score-adj,或给容器设置 --oom-kill-disable,来绕过这些保护。

Linux 内核 OOM 管理的更多说明见 Out of Memory Management。

可以采取以下措施,降低内存耗尽导致系统不稳定的风险:

  • 上线前进行测试,了解应用的内存需求。
  • 确保应用只运行在资源充足的宿主机上。
  • 按下文所述限制容器可使用的内存。
  • 谨慎配置 Docker 宿主机的交换空间。交换空间比内存慢,但可以在系统内存不足时提供缓冲。
  • 考虑把容器转换为 服务,并使用服务级约束与节点标签,让应用只运行在内存足够的宿主机上。

限制容器可使用的内存

Docker 可以实施硬内存限制和软内存限制。硬限制规定容器不能使用超过固定数量的内存;软限制通常允许容器按需使用内存,只有满足特定条件时才起作用,例如内核发现宿主机内存不足或出现资源争用。

某些选项单独使用与组合使用时会产生不同效果。大多数选项接收一个正整数,后跟 b、k、m、g 后缀,分别表示字节、千字节、兆字节和吉字节。

选项 含义
-m 或 --memory= 容器可使用的最大内存。设置此选项时允许的最小值为 6m,即 6 兆字节。
--memory-swap 控制容器的内存与交换空间预算。它与 --memory 的组合语义见下文。
--memory-swappiness 宿主机内核默认可换出容器使用的一部分匿名页。可设为 0 至 100,调整这个比例,具体见下文。
--memory-reservation 指定小于 --memory 的软限制。Docker 检测到宿主机资源争用或内存不足时,该限制起作用。要让它优先发挥作用,必须低于 --memory。由于这是软限制,不能保证容器绝不超过该值。
--oom-kill-disable 默认情况下发生 OOM 时,内核会终止容器中的进程。此选项可改变该行为。只应在同时设置了 -m/--memory 的容器上禁用 OOM killer;若未设置 -m,宿主机可能耗尽内存,内核可能不得不终止宿主机上的系统进程。

关于 cgroup 与内存的更多说明,见 Memory Resource Controller。这些内核资料包含 cgroup v1 路径,具体支持情况应结合实际宿主内核和 cgroup 版本核查。

--memory-swap 的详细语义

--memory-swap 是一个修饰参数,只有同时设置 --memory 时才有意义。容器用完可用 RAM 后,交换空间允许它把额外的内存需求写入磁盘。频繁换出会带来性能损失。

不同取值的效果如下:

  • 若 --memory-swap 为正整数,则必须同时设置 --memory 与 --memory-swap。--memory-swap 表示内存与交换空间可使用的总量,--memory 限制非交换内存。例如 --memory="300m"、--memory-swap="1g" 时,源文示例把预算解释为 300m 内存与 700m(1g - 300m)交换空间。具体换算应按运行时单位语义核对。
  • 设为 0 时,此设置被忽略,按未设置处理。
  • 若与正值 --memory 相同,容器不能使用交换空间。
  • 若不设置 --memory-swap,但设置了 --memory,并且宿主机配置了交换空间,则容器可以使用与 --memory 数值相同的交换空间。例如只设置 --memory="300m" 时,内存与交换空间总预算可为 600m。
  • 显式设为 -1 时,容器的交换空间不设自身上限,但仍受宿主机可用交换空间总量限制。
  • 在容器内,free 等工具显示的是宿主机可用交换空间,并非容器实际可使用的交换空间。不要依赖这些输出判断容器是否能够使用交换空间。

防止容器使用交换空间

把 --memory 与 --memory-swap 设为相同的正值,就能阻止容器使用交换空间。这是因为 --memory-swap 控制内存与交换空间的合计值,而 --memory 只控制物理内存。

--memory-swappiness 的详细语义

  • 值为 0 时,关闭匿名页换出。
  • 值为 100 时,所有匿名页都可被换出。
  • 未设置时,默认继承宿主机的值。

CPU

默认情况下,每个容器使用宿主机 CPU 周期的能力都没有限制。可以配置不同约束来限制某个容器的 CPU 使用。多数用户使用默认 CFS 调度器,也可以配置实时调度器。

配置默认 CFS 调度器

CFS 是 Linux 内核对普通进程使用的 CPU 调度器。多个运行时参数可以控制容器获得的 CPU 资源;使用这些设置时,Docker 会修改宿主机上该容器的 cgroup 设置。

选项 含义
--cpus=<value> 指定容器最多可使用多少 CPU 资源。宿主机有两个 CPU 时,设置 --cpus="1.5" 表示最多使用相当于一个半 CPU 的资源,等价于 --cpu-period="100000" 与 --cpu-quota="150000"。
--cpu-period=<value> 设置 CFS 调度周期,与 --cpu-quota 配合。默认 100000 微秒,即 100 毫秒,多数用户无需修改。多数场景使用 --cpus 更方便。
--cpu-quota=<value> 设置 CFS 配额:每个 --cpu-period 周期中,容器在被限流前可使用的微秒数,形成实际使用上限。多数场景使用 --cpus 更方便。
--cpuset-cpus 限定容器可使用的 CPU 或核心。多 CPU 宿主机可使用逗号列表或连字符范围,编号从 0 开始。例如 0-3 使用前四个 CPU,1,3 使用第二与第四个。
--cpu-shares 默认权重 1024,可设更大或更小来改变竞争时获得 CPU 周期的比例。只有 CPU 资源紧张时才实施;资源充足时,各容器仍可按需使用。因此这是软限制,不保证或预留特定 CPU 资源,也不会阻止容器在 Swarm 模式下被调度。

宿主机只有一个 CPU 时,下列命令让容器每秒最多使用相当于 50% 的 CPU:

$ docker run -it --cpus=".5" ubuntu /bin/bash

这等价于手动设置 --cpu-period 与 --cpu-quota:

$ docker run -it --cpu-period=100000 --cpu-quota=50000 ubuntu /bin/bash

配置实时调度器

无法使用 CFS 调度器的任务,可以考虑为容器配置实时调度器。必须先正确配置宿主机内核,然后配置 Docker 守护进程和单个容器。

CPU 调度和优先级属于高级内核功能。多数用户无需改变默认值。错误的设置可能使宿主系统不稳定,甚至无法使用。

配置宿主机内核

运行 zcat /proc/config.gz | grep CONFIG_RT_GROUP_SCHED,或者检查 /sys/fs/cgroup/cpu.rt_runtime_us 文件是否存在,确认 Linux 内核启用了 CONFIG_RT_GROUP_SCHED。如何配置内核实时调度器,请查阅操作系统文档。这些检查路径来自源文,适用性需要按内核及 cgroup 版本核查。

配置 Docker 守护进程

使用实时调度器时,启动 Docker 守护进程并设置 --cpu-rt-runtime,指定每个运行周期为实时任务保留的最大微秒数。例如默认周期为 1000000 微秒(1 秒)时,设置 --cpu-rt-runtime=950000,使实时容器每个周期最多运行 950000 微秒,并为非实时任务至少保留 50000 微秒。

对于使用 systemd 的系统,要让设置持久生效,可为 docker 服务创建 systemd 单元文件。参见通过 systemd 单元文件 配置守护进程代理的相关说明。

配置单个容器

用 docker run 启动容器时,可以传入多个参数控制 CPU 优先级。合适的取值请查阅操作系统文档或 ulimit 文档。

选项 含义
--cap-add=sys_nice 授予容器 CAP_SYS_NICE 能力,允许它调整进程 nice 值(包括降低值以提高调度优先级)、设置实时调度策略、设置 CPU 亲和性等。源文将 nice 调整写为提高数值,这里按 Linux capabilities(7) 校正措辞。
--cpu-rt-runtime=<value> 在 Docker 守护进程实时调度周期中,容器以实时优先级运行的最大微秒数;同时需要 --cap-add=sys_nice。
--ulimit rtprio=<value> 容器允许使用的最大实时优先级;同时需要 --cap-add=sys_nice。

源文用 debian:jessie 容器示范这三个参数。该镜像属于历史示例,不能据此认定其适合现行生产环境。

$ docker run -it \
    --cpu-rt-runtime=950000 \
    --ulimit rtprio=99 \
    --cap-add=sys_nice \
    debian:jessie

如果内核或 Docker 守护进程配置不正确,就会出现错误。

GPU

如何在容器中访问 NVIDIA GPU,参见 GPU access。

Copyright 2013-2026 Docker, Inc. 原文:Resource constraints。文档由 Docker 文档团队及贡献者提供,按 Apache License 2.0 发布;许可范围证据。本版本翻译为中文,补充了内核版本、单位换算与历史镜像提示,代码及示例输出保持原样;未执行示例。许可不授权使用商标。

Apache License 2.0 完整许可
Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.
      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.
      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.
      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).
      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.
      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."
      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.
   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.
   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.
   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and
      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and
      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.
      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.
   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.
   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.
   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.
   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.
   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.
   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.
      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "{}"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.
   Copyright 2016 Docker, Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容