7.5.8 定义Kubernetes服务

本示例中的内部服务是基于Nginx实现的,首先为Nginx服务器创建配置文件,以挂载上述证书。以域名myexample.com的内部服务为例,定义请求根路径直接返回字样“Welcome to myexample.com!This is one custom Istio Ingress Gateway powered by cert-manager!”及状态码200。

myexample-nginx.conf的具体内容如下:


events {
}

http {
  log_format main '$remote_addr - $remote_user [$time_local]  $status '
  '"$request" $body_bytes_sent "$http_referer" '
  '"$http_user_agent" "$http_x_forwarded_for"';
  access_log /var/log/nginx/access.log main;
  error_log  /var/log/nginx/error.log;

  server {
    listen 80;

    location / {
        return 200 'Welcome to myexample.com! This is one custom Istio Ingress Gateway powered by cert-manager!';
        add_header Content-Type text/plain;
    }
  }
}

创建Kubernetes Conf igMap存储Nginx服务器的配置:


kubectl create configmap myexample-nginx-configmap --from-file=nginx.conf=./myexample-nginx.conf

设置命名空间default,启用Sidecar自动注入:


kubectl label namespace default istio-injection=enabled

注意

该Sidecar自动注入的Label需要在Ingress Gateway创建之后再进行标注,以确保Ingress Gateway不会自动注入,或者不启用自动注入,通过手工注入完成。

部署NGINX服务器,创建域名myexample.com的内部服务:


kubectl apply -f - <<EOF
apiVersion: v1
kind: Service
metadata:
  name: myexampleapp
  labels:
    app: myexampleapp
spec:
  ports:
  - port: 80
    protocol: TCP
  selector:
    app: myexampleapp
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myexampleapp
spec:
  selector:
    matchLabels:
      app: myexampleapp
  replicas: 1
  template:
    metadata:
      labels:
        app: myexampleapp
    spec:
      containers:
      - name: nginx
        image: nginx
        ports:
        - containerPort: 80
        volumeMounts:
        - name: nginx-config
          mountPath: /etc/nginx
          readOnly: true
      volumes:
      - name: nginx-config
        configMap:
          name: myexample-nginx-configmap

EOF

接下来,创建一个自定义网关配置对象。以域名myexample.com为例,创建Istio自定义网关配置对象的代码如下所示:


apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  annotations:
  name: istio-myexample-customingressgateway
  namespace: default
spec:
  selector:
    istio: istio-myexample-customingressgateway
  servers:
  - hosts:
    - '*.myexample.com'
    port:
      name: http
      number: 80
      protocol: HTTP
    tls:
      httpsRedirect: true
  - hosts:
    - '*.myexample.com'
    port:
      name: https
      number: 443
      protocol: HTTPS
    tls:
      mode: SIMPLE
      privateKey: /etc/istio/ingressgateway-certs/tls.key
      serverCertificate: /etc/istio/ingressgateway-certs/tls.crt