一、创建服务

(1)前端服务

将前端项目打成镜像,创建服务,我这里访问前端服务是

http://172.16.10.158:32666/view/index.html
http://172.16.10.158:32667/view2/index.html

(2)查看创建的服务

[root@k8s-master cpaas-manager]# kubectl get svc
NAME                         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
app-service-01               NodePort    10.101.13.205    <none>        80:32666/TCP   12m
app-service-02               NodePort    10.104.215.15    <none>        80:32667/TCP   4s

二、创建IngressRoute

(1)app-ingressroute.yaml

[root@k8s-master 2]# cat app-ingressroute.yaml
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: app-route
  annotations:
    kubernetes.io/ingress.class: traefik-v2.5
spec:
  entryPoints:
    - web
  routes:
  - match: Host(`www.iscas.com`) && PathPrefix(`/view`)
    kind: Rule
    services:
    - name: app-service-01
      port: 80
  - match: Host(`www.iscas.com`) && PathPrefix(`/view2`)
    kind: Rule
    services:
    - name: app-service-02
      port: 80

(2)创建

[root@k8s-master 2]# kubectl create -f app-ingressroute.yaml
ingressroute.traefik.containo.us/app-route created

(3)配置ip域名

172.16.10.158   www.iscas.com

(4)访问服务

http://www.iscas.com/view/index.html
http://www.iscas.com/view2/index.html

三、使用Middleware

Traefik Middlewares 中间件是用于流量进入 Traefik 且通过定义的路由规则后,转发到对应后端服务前,在这期间对该流量进行加工的操作,它支持:

    重试、压缩、缓冲、断路器
    header 管理、错误页、中间件链
    服务限流、同一主机并发请求限制
    基本认证、IP 白名单、摘要认证、转发鉴权验证
    regex 请求重定向、scheme 请求重定向、请求 URL 替换、regex 请求 URL 替换、删除 URL 前缀、regex 删除 URL 前缀、添加 URL 前缀

这里简单使用去除请求路径前缀中间件

(1)app-middleware.yaml

[root@k8s-master 2]# cat app-middleware.yaml
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: app-middleware   ##设置中间件名称,要和路由规则中的名称一致
spec:
  stripPrefix:
    prefixes:
      - /front-01        ##设置要去除的前缀

(2)创建

[root@k8s-master 2]# kubectl create -f app-middleware.yaml
middleware.traefik.containo.us/app-middleware created

(3)修改 app-ingressroute.yaml

[root@k8s-master 2]# cat app-ingressroute.yaml
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: app-route
  annotations:
    kubernetes.io/ingress.class: traefik-v2.5
spec:
  entryPoints:
    - web
  routes:
  - match: Host(`www.iscas.com`) && PathPrefix(`/front-01`)  ## 修改路径
    kind: Rule
    services:
    - name: app-service-01
      port: 80
    middlewares:
    - name: app-middleware       ##指定使用的中间件
  - match: Host(`www.iscas.com`) && PathPrefix(`/view2`)
    kind: Rule
    services:
    - name: app-service-02
      port: 80

(4)创建

[root@k8s-master 2]# kubectl create -f app-ingressroute.yaml
ingressroute.traefik.containo.us/app-route created

(5)访问服务

第一个服务的访问方式变成了

http://www.iscas.com/front-01/view/index.html
Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐