目标:完成Ingress的泛域名配置,通过lua脚本转发到后端service
Service, Deployment配置
kind: Service apiVersion: v1 metadata: name: aimaster-nginx-service-wildcard spec: selector: aimaster.lenovo.com/service.pod: nginx-service-wildcard ports: - protocol: TCP port: 8080 targetPort: http name: http --- apiVersion: apps/v1 kind: Deployment metadata: name: aimaster-nginx-service-wildcard spec: selector: matchLabels: aimaster.lenovo.com/service.pod: "nginx-service-wildcard" replicas: 1 template: metadata: labels: aimaster.lenovo.com/service.pod: "nginx-service-wildcard" spec: affinity: podAntiAffinity: preferredDuringSchedulingIgnoredDuringExecution: - weight: 1 podAffinityTerm: labelSelector: matchExpressions: - key: aimaster.lenovo.com/service.pod operator: In values: - nginx-service-wildcard topologyKey: "kubernetes.io/hostname" containers: - name: service image: "openresty/openresty:1.17.8.2-5-centos" ports: - name: http containerPort: 80 volumeMounts: - mountPath: /usr/local/openresty/nginx/conf/nginx.conf name: config-volume subPath: nginx.conf volumes: - name: config-volume hostPath: path: /home/nginx_wildcard/ type: Directory
ingress 配置
apiVersion: networking.k8s.io/v1beta1 kind: Ingress metadata: name: aimaster-nginx-ingress-wildcard namespace: default spec: rules: - host: "*.sub.test.com" http: paths: - path: / backend: serviceName: aimaster-nginx-service-wildcard servicePort: http
nginx.conf
worker_processes 1; error_log /error.log debug; pid /nginx.pid; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /access.log main; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; resolver local=on ipv6=off; server { listen 80; location / { set $service ''; rewrite_by_lua_block { local host = ngx.var.host local regex = "([0-9a-zA-Z-]+).([0-9a-zA-Z-]+).sub.test.com" local m = ngx.re.match(host, regex) if m then ngx.log(ngx.STDERR, "service: " .. m[1] .. " ns: " .. m[2]) ngx.var.service = m[1] .. "." .. m[2].. ".svc.cluster.local:8099" ngx.log(ngx.STDERR, "service: " .. ngx.var.service) end } proxy_pass http://$service; } } }
nginx.conf配置注意事项
1. resolver local=on ipv6=off; 这个配置使用local=on是openresty中带有的一个参数,会使用/etc/resolve.conf文件进行解析域名
2. 由于使用了kube-dns,端口号可以自己设置,8099替换成servivce的端口。
使用:
先把/etc/hosts文件修改指向对应的nginx-controller地址,
xxx.xxx.xxx.xxx <service name>.sub.test.com
然后使用curl <service name>.sub.test.com 来查看访问结果