`
can_do
  • 浏览: 266301 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

K8S中Nginx ingress或者Openresty ingress插入原生代码

阅读更多
一、场景
K8S中nginx ingress一般负载的是pod的service,但如何代理到一个外部服务A?

二、前提

K8S的docker中可以访问外部服务A,即网络上是打通的,可以事先测试确认好;

三、解决方案

1> 通过ingress yaml语法代理,简单的反向代理是可以的,但涉及附加参数的调整的话,

该方案不适用;
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: yourdomain
  namespace: yournamespace
spec:
  rules:
  - host: yourdomain.cnd.com
    http:
      paths:
      - path: /
        backend:
          serviceName: yourdomain
          servicePort: 18306
	  - path: /yourown
        backend:
          serviceName: yourdomain-cnd
          servicePort: 8888


注意:
1> 此处servicename的写法上,仅支持,英文字母开头和结束的,可以有连字符【-】,其他字符不支持,比如子域名中的dot【.】,因此此写法不能直接路由到外部域名的服务A
2> 如果要附加调整一些请求header参数,比如:host,此写法不好支持,暂没有发现;

2> 通过ingress 使用snippet注入类原生代码;
nginx-ingress中可以使用以下snippet annotion,

一个成功使用configuration的snippet,如下:
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: yourfromdomain
  namespace: your-custom-namespace
  annotations:
    nginx.ingress.kubernetes.io/configuration-snippet: |
      if ($request_uri ~ "^\/backendbac|\/backenddef|\/backendxyz") {
          more_set_input_headers "Host: youregateway.cnd.com";
          proxy_pass http://youregateway.cnd.com:8888;
          break;
      }
spec:
  rules:
  - host: yourfromdomain.cnd.com
    http:
      paths:
      - path: /
        backend:
          serviceName: yourfromdomain
          servicePort: 18306

## more_set_headers "Host: youregateway.responsecnd.com";


注意:
1> 此处对原生的nginx proxy_set_header不适用,而要使用:more_set_input_headers来设置request header参数;
2> 另外,more_set_headers可以设置response中header参数;

另一个通过rewrite而不是反向代理实现的例子如下:

---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: yourfromdomain
  namespace: your-custom-namespace
  annotations:
    nginx.ingress.kubernetes.io/configuration-snippet: |
      rewrite /yourbackendapi/(.*)  /yoursecondapi/$1 break;
spec:
  rules:
  - host: yourfromdomain.cnd.com
    http:
      paths:
      - path: /
        backend:
          serviceName: yourfromdomain
          servicePort: 28206



四、同步循环模式【synchronization loop pattern】
Avoiding outage from wrong configuration
Because the ingress controller works using the synchronization loop pattern, it is applying the configuration for all matching objects. In case some Ingress objects have a broken configuration, for example a syntax error in the nginx.ingress.kubernetes.io/configuration-snippet annotation, the generated configuration becomes invalid, does not reload and hence no more ingresses will be taken into account.

这就是为什么ingress yaml文件中annotation的注解部分代码,有语法错误时,其配置不会同步到nginx.conf,而是采用旧文件,遵循既有规则优先的原则。




五、参考官方
https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/#custom-nginx-upstream-vhost

https://kubernetes.github.io/ingress-nginx/how-it-works/


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics