「Docker Container」- 查看容器资源,限制容器资源 @20210123

问题描述

在服务上,有很多容器没有做资源限制。在峰值出现时,他们会耗尽服务器资源,影响其他容器的运行。

因此,我们需要对这些容器进行资源限制(批量处理)。

该笔记将记录:1)如何批量对容器进行资源限制,2)并设置可用资源上限当前已用资源加上”预留资源“

解决方案

查看资源用量(并排序)

docker stats --no-stream --format "table {
    
    {.Name}}\t{
    
    {.Container}}\t{
    
    {.CPUPerc}}\t{
    
    {.MemUsage}}" \
    | sort -k 4 --human-numeric-sort

批量限制容器资源

DOCKER_API_VERSION=v1.39

for container_id in $(docker ps -q)
do

    # colorful title
    echo "####### Updating Container ${container_id}" | grep --color -E '.'

    # 我们设置,内存上限 = 当前内存使用 + 500M
    memory_limit=$(curl -s --unix-socket /var/run/docker.sock \
                        "http://ph/${DOCKER_API_VERSION}/containers/${container_id}/stats?stream=false" \
                       | jq '.memory_stats | ((.usage - .stats.cache) + 500 * 1024 * 1024)')
    # 执行设置
    docker update --cpu-shares 512 --memory "$memory_limit" "$container_id"
    
done

相关链接

Runtime options with Memory, CPUs, and GPUs | Docker Documentation
Update configuration of containers

参考文献

WikiNotes/查看容器资源,限制容器资源
Runtime options with Memory, CPUs, and GPUs | Docker Documentation
Update configuration of containers
docker stats | Docker Documentation
Sort by memory usage in docker stats - Stack Overflow

猜你喜欢

转载自blog.csdn.net/u013670453/article/details/113043929