企业入门实战- - docker之docker安全设置
一.容器内存控制
创建自定义大小的容器
docker run -m 200M -d --name demo nginx

cd /sys/fs/cgroup/memory/docker/
进入 刚刚创建的id
cat memory.memsw.limit_in_bytes

设置内容写入大小
cd /sys/fs/cgroup/memory
mkdir x1
cd x1

echo 209715200 > memory.limit_in_bytes 限制写入大小为200M
 安装cgroup工具
yum install -y libcgroup-tools.x86_

测试:在/dev/shm 目录下 每次测试前需要删除掉创建的bigfile
100M
free -m
cgexec -g memory:x1 dd if=/dev/zero of=bigfile bs=1M count=100
free -m

200M
free -m
cgexec -g memory:x1 dd if=/dev/zero of=bigfile bs=1M count=200
free -m

300M
ee -m
cgexec -g memory:x1 dd if=/dev/zero of=bigfile bs=1M count=300
free -m
 这时候会发现多出来的100M被放到了swap分区中
关闭swap分区测试
cd /dev/shm
rm -fr bigfile
swapoff -a
cgexec -g memory:x1 dd if=/dev/zero of=bigfile bs=1M count=300 ## 会被kill掉

打开swap分区 设置容器swap不能写入
cd /sys/fs/cgroup/memory/x1
echo 209715200 > memory.memsw.limit_in_bytes ## 最大写入200M
 测试:
cd /dev/shm
cgexec -g memory:x1 dd if=/dev/zero of=bigfile bs=1M count=300 ## 直接报错
 虽然导入了300M但是只能写入200M 
二.cpu配额
这里的虚拟机只有一个cpu
cd /sys/fs/cgroup/cpu ## 进入目录
mkdir x2
cd x2/
ls
 设定cpu配额
cat cpu.shares
echo 100 > cpu.shares

dd if=/dev/zero of=/dev/null & ## 打入后台
top 查看dd的进程号

cat tasks
echo 14768 > tasks ## dd命令的进程号写入task中
 再次运行此命令
dd if=/dev/zero of=/dev/null &
top
 将第二个写入命令的进程号写入task文件中
 
cpu配额1024
cd /sys/fs/cgroup/cpu/x2/
echo 1024 > cpu.shares
cat cpu.share

echo 20000>cpu.cfs quota us
cat cpu.cfs_quota_us 配额
cat cpu.cfs_period_us 最大额度
top 查看两个dd命令的cpu占用额度
 20000是100000的十分之一 所以两个dd进程共所占10% 
三.Block IO
–device-write-bps限制写设备的bps
docker run -it --rm --device-write-bps /dev/vda:30MB rhel7 bash
bash-4.2# dd if=/dev/zero of=bigfile bs=1M count=200
200+0 records in
200+0 records out
209715200 bytes (210 MB) copied, 0.189837 s, 1.1 GB/s
bash-4.2# dd if=/dev/zero of=bigfile bs=1M count=200 oflag=direct
200+0 records in
200+0 records out
209715200 bytes (210 MB) copied, 6.82782 s, 30.7 MB/s
两个的再入速度不一样 
四.docker安全加固
利用LXCFS增强docker容器隔离性和资源可见性 安装lxcf插件
yum install lxcfs-2.0.5-3.el7.centos.x86_64.rpm -y

lxcfs /var/lib/lxcfs/ &
ps ax


cd /var/lib/lxcfs/
ls

docker run -it -m 256m \
-v /var/lib/lxcfs/proc/cpuinfo:/proc/cpuinfo:rw \
-v /var/lib/lxcfs/proc/diskstats:/proc/diskstats:rw \
-v /var/lib/lxcfs/proc/meminfo:/proc/meminfo:rw \
-v /var/lib/lxcfs/proc/stat:/proc/stat:rw \
-v /var/lib/lxcfs/proc/swaps:/proc/swaps:rw \
-v /var/lib/lxcfs/proc/uptime:/proc/uptime:rw \
ubuntu
free -m

docker run -it --rm busyboxplus
ip addr
ip link set down eth0 会报没有权限
 设置特权级运行的容器:–privileged=true 默认为false
docker run-it--rm--privileged busyboxplus 设置特权级运行的容器
ip link set down eth0
 设置容器白名单:–cap-add
docker run -it --rm --cap-add=NET_ADMIN busyboxplus 添加容器运行白明单
ip addr
ip addr add 172.25.0.100/24 dev eth0
ip addr del 172.25.0.100/24 dev eth0
 
|