方块糖的工坊
方块糖的工坊

动态扩展Docker容器空间大小

docker容器默认的空间是10G,通过如下命令可以设定docker容器的默认空间大小为20G:

docker -d --storage-opt dm.basesize=20G

修改过后需要重启docker,无法做到动态给运行容器指定大小,下面是我将动态扩容步骤整合成的Shell脚本:

#!/bin/bash
#This script is dynamic modify docker container disk
#Author fangguitang
if [ -z $1 ] || [ -z $2 ]; then
    echo "Usage: container_name increase_capacity"
    echo "Example: I want increase 11G to test"
    echo "The command is:   sh `basename $0` test 11"
    exit 1
fi

if [ ! `docker inspect  -f {{.State.Running}} $1` ];then
    echo "The container $1 is no exist!"
    exit 1
fi

device_name=`docker inspect -f {{.GraphDriver.Data.DeviceName}} $1`
disk=$(($2*1024*1024*1024/512))
now_disk=`dmsetup table $device_name|awk '{print $2}'`

if [ $disk -lt $now_disk ];then
    echo "I can't shink container $1 from $(($now_disk*512/1024/1024/1024))G to ${2}G!I only modify contanier increase disk!"
    exit 1
fi

#将新的扇区大小写入
dmsetup table $device_name|sed "s/0 [0-9]* thin/0 $disk thin/"|dmsetup load $device_name
dmsetup resume $device_name

echo "file system :" `df -hT | grep "^/dev/sda1" | awk '{print $2}'`

if [[ `df -hT | grep "^/dev/sda1" | awk '{print $2}'` == "xfs" ]];then
    #xfs系统 Centos7
    xfs_growfs -d /dev/mapper/$device_name
elif [[ `df -hT | grep "^/dev/sda1" | awk '{print $2}'` == ext* ]];then
    #ext2、3、4系统 Centos6
    resize2fs /dev/mapper/$device_name
fi

if [ $? -eq 0 ];then
    echo "dynamic container $1 disk to ${2}G is success!"
else
    echo "dynamic container $1 disk to ${2}G is fail!"
fi

使用示例:

# 赋予可执行权限
chmod +x dynamic_modify_docker_disk_el7.sh
# 将nodejs容器的磁盘扩大到50GB
sh dynamic_modify_docker_disk_el7.sh nodejs 50

脚本下载:dynamic_modify_docker_disk_el7.sh

发表回复

textsms
account_circle
email

方块糖的工坊

动态扩展Docker容器空间大小
docker容器默认的空间是10G,通过如下命令可以设定docker容器的默认空间大小为20G: docker -d --storage-opt dm.basesize=20G 修改过后需要重启docker,无法做到动态给运行容器指…
扫描二维码继续阅读
2019-08-30