Coup de Grace

K8s后日谈 负载均衡traefik

需要的知识储备:

Traefik扮演的是Ingress抽象中负载均衡器与Ingress Controller的角色

路由与元数据访问都是Traefik来进行.


功能

以上的功能来自官网,日后的使用中会逐步进行探索.

姑且会更新在本文中.


部署本体

内容来自这里,官网文档实际已经不够新了.

我们使用deploy先部署几个应用上去,推荐将副本修改为node-1的数目保持高可用.

注意traefik的pod是占用hostPort: 80的,所以每台node上最多一个.

其次我们部署一个Service,用来稍作聚合.

可以如下:

apiVersion: v1
kind: Service
metadata:
  name: traefik-svc
  namespace: kube-system
spec:
  selector:
    k8s-app: traefik-ingress-lb
  ports:
  - name: svc
    port: 80
    targetPort: 80
    nodePort: 30001
  type: NodePort

部署其他

实际这个ui也是以ingress暴露出来的.ui的话8080端口的部分还是修改一下,换成小众一点的.

我们自己部署应用也是同理.

  1. 部署RC/deploy
  2. 部署Service
  3. 部署Ingress
  4. 设置dns/hosts到traefik所在机器上测试
  5. 前挂负载均衡,将host指向几个node
  6. done.

原理: traefik监听本地的80端口,遇到serverName匹配并且路由命中的时候生效.


一些


配置文件实例

traefik-deploy

apiVersion: v1
kind: Deployment
apiVersion: extensions/v1beta1
metadata:
  name: traefik-ingress-controller
  namespace: kube-system
  labels:
    k8s-app: traefik-ingress-lb
spec:
  replicas: 2
  selector:
    matchLabels:
      k8s-app: traefik-ingress-lb
  template:
    metadata:
      labels:
        k8s-app: traefik-ingress-lb
        name: traefik-ingress-lb
    spec:
      terminationGracePeriodSeconds: 60
      volumes:
      - name: ssl
        secret:
          secretName: traefik-cert
      - name: config
        configMap:
          name: traefik-conf
      hostNetwork: true
      containers:
      - image: registry.yourcompany.com/traefik:v1.1.1
        name: traefik-ingress-lb
        volumeMounts:
        - mountPath: "/ssl"
          name: "ssl"
        - mountPath: "/config"
          name: "config"
        resources:
          limits:
            cpu: 200m
            memory: 30Mi
          requests:
            cpu: 100m
            memory: 20Mi
        ports:
        - name: http
          containerPort: 80
          hostPort: 80
        - name: https
          containerPort: 443
          hostPort: 443
        - name: admin
          containerPort: 9002
        args:
        - --configfile=/config/traefik.toml
        - --web
        - --kubernetes

traefik-svc

apiVersion: v1
kind: Service
metadata:
  name: traefik-svc
  namespace: kube-system
spec:
  selector:
    k8s-app: traefik-ingress-lb
  ports:
  - name: svc
    port: 80
    targetPort: 80
    nodePort: 30001
  type: NodePort

traefik-ui

---
apiVersion: v1
kind: Service
metadata:
  name: traefik-web-ui
  namespace: kube-system
spec:
  selector:
    k8s-app: traefik-ingress-lb
  ports:
  - name: web
    port: 9002
    targetPort: 9002
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: traefik-web-ui
  namespace: kube-system
spec:
  rules:
  - host: traefik-ui.local
    http:
      paths:
      - path: /
        backend:
          serviceName: traefik-web-ui
          servicePort: web

done.