k8s水平扩容

简介

k8s 的好处就是可以弹性水平扩容和纵向扩容,平时纵向扩容用的不太多,所以今天说说水平扩容,在创建hpa之前你要确定集群中已经安装了metrics-server,我使用的是k3s,直接自带

操作

基于

https://kubernetes.io/zh/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough/

首先创建需要的容器,下面是dockerfile

1
2
3
FROM php:5-apache
COPY index.php /var/www/html/index.php
RUN chmod a+rx index.php

下面是index.php

1
2
3
4
5
6
7
<?php
  $x = 0.0001;
  for ($i = 0; $i <= 1000000; $i++) {
    $x += sqrt($x);
  }
  echo "OK!";
?>

原理就是当你访问index.php的时候会进行一个循环计算来提高cpu的使用率

编译镜像

docker build . -t registry.bboysoul.cn/hpa-example

然后推送到仓库

docker push registry.bboysoul.cn/hpa-example:latest

然后创建一个svc和deployment

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
apiVersion: apps/v1
kind: Deployment
metadata:
  name: php-apache
spec:
  selector:
    matchLabels:
      run: php-apache
  replicas: 1
  template:
    metadata:
      labels:
        run: php-apache
    spec:
      imagePullSecrets:
      - name: regcred
      containers:
      - name: php-apache
        image: registry.bboysoul.cn/hpa-example:latest
        ports:
        - containerPort: 80
        resources:
          limits:
            cpu: 500m
          requests:
            cpu: 200m

---

apiVersion: v1
kind: Service
metadata:
  name: php-apache
  labels:
    run: php-apache
spec:
  type: LoadBalancer
  ports:
  - port: 80
  selector:
    run: php-apache

svc类型是lb

kubectl apply -f deployment.yaml

之后创建hpa

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
  name: php-apache
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: php-apache
  minReplicas: 1
  maxReplicas: 10
  targetCPUUtilizationPercentage: 50

指定当pod的cpu大于50%的时候扩展,而且最大的个数不超过10个

kubectl apply -f hpa.yaml

创建成功之后查看lb的ip,然后访问index.php

while sleep 0.01; do curl 10.10.100.167; done

之后使用下面命令查看pod的cpu情况

kubectl top pods -A

不出意外的话,等一段时间后pod就会自动增加

当你停止之后pod也会自动删除

欢迎关注我的博客 www.bboy.app

Have Fun