docker 是一个非常不错的容器, 让我们可以先把程序部署在镜像中, 然后再放到某个实体机器上跑. 若一个实体机中我们使用多个容器, 我们可能需要限制一个容器占用的系统资源. 比如内存, CPU 等

docker run reference 中提供了一些参数来处理系统限制.

内存,CPU的系统限制如下:

Option Description
-m, --memory="" Memory limit (format: <number>[<unit>] , where unit = b, k, m or g)
--memory-swap="" Total memory limit (memory + swap, format: <number>[<unit>], where unit = b, k, m or g)
-c, --cpu-shares=0 CPU shares (relative weight)
--cpu-period=0 Limit the CPU CFS (Completely Fair Scheduler) period
--cpuset-cpus="" CPUs in which to allow execution (0-3, 0,1)
--cpuset-mems="" Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems.
--cpu-quota=0 Limit the CPU CFS (Completely Fair Scheduler) quota
--blkio-weight=0 Block IO weight (relative weight) accepts a weight value between 10 and 1000.
--oom-kill-disable=false Whether to disable OOM Killer for the container or not.
--memory-swappiness="" Tune a container’s memory swappiness behavior. Accepts an integer between 0 and 100.

设置内存处理标志

Option Result
memory=inf, memory-swap=inf (default) There is no memory limit for the container. The container can use as much memory as needed.
memory=L<inf, memory-swap=inf (specify memory and set memory-swap as -1) The container is not allowed to use more than L bytes of memory, but can use as much swap as is needed (if the host supports swap memory).
memory=L<inf, memory-swap=2*L (specify memory without memory-swap) The container is not allowed to use more than L bytes of memory, swap *plus* memory usage is double of that.
memory=L<inf, memory-swap=S<inf, L<=S (specify both memory and memory-swap) The container is not allowed to use more than L bytes of memory, swap *plus* memory usage is limited by S.

比如我们可以使用

docker run -ti -m 300M --memory-swap -1 centos /bin/bash

其中 -m 300M 限制内存最多占用 300MB, 此处支持 B, K, M, G 等.

--memory-swap -1 表示交换分区不限制

docker run -ti --memory-swappiness=0 centos /bin/bash

表示 docker 不使用交换分区.

docker run -ti --cpuset-cpus="1,3" centos /bin/bash

表示 docker 仅使用 1, 3 两个 cpu 进程

docker run -ti --cpuset-cpus="0-2" centos /bin/bash

表示 docker 仅使用 0, 1, 2 三个 cpu 进程

docker run -ti --cpuset-mems="1,3" centos /bin/bash

表示 docker 仅使用 1, 3 两个 cpu 进程管理的内存

docker run -ti --cpuset-mems="0-2" centos /bin/bash

表示 docker 仅使用 0, 1, 2 三个 cpu 进程管理的内存

--cpu-period 和 --cpu-quota 一般一起使用.

docker run -ti --cpu-period=50000 --cpu-quota=25000 centos /bin/bash

这样表示一个 cpu 每 50ms 占用 cpu 50% 的资源占用.

References:

  • Docker —— 从入门到实践 http://yeasy.gitbooks.io/docker_practice/content/index.html
  • Docker run reference https://docs.docker.com/reference/run/#runtime-constraints-on-resources
来自的你,很高兴你能看到这儿。若本文对你有所用处,或者内容有什么不足之处,敬请毫不犹豫给个回复。谢谢!