kubernetes ingres-nginx高级配置

通过configmap修改nginx controller的一些全局变量

通过启动nginx controller的yaml文件,其实我们可以看出来,在启动controller的时候,向启动命令传递了一大堆参数,包括–default-backend-service以及–apiserver-host等。更多的参数,可以直接参考相关文档

nginx controller本质上就是一个nginx代理,这个代理使用了一大堆nginx默认参数启动。而在某些特定场景下,这些我们需要定制这些参数以更适用于我们的需求。在controller启动的时候,提供了一个–configmap的参数,我们可以将需要定制的参数保存到一个configmap中,并在controller启动的时候,来读取这个configmap,获取其值,应用到controller中。具体哪些值可以通过configmap来传递,可以直接参考相关文档
https://github.com/kubernetes/ingress-nginx/blob/master/docs/user-guide/nginx-configuration/configmap.md

一、使用ConfigMap

确保指定启动Ingress控制器时要使用的configmaps资源。
需要注意-

1
2
3
4
5
6
7
8
9
10
11
12
kind: ConfigMap 
apiVersion: v1
metadata:
name: nginx-configuration
namespace: ingress-nginx
labels:
app: ingress-nginx
data:
client-header-buffer-size: "4k"
proxy-connect-timeout: "40"
proxy-read-timeout: "110"
proxy-send-timeout: "110"

创建配置资源:

1
2
3
4
 kubectl apply -f nginx-configuration.yaml
kubectl get cm nginx-configuration -n ingress-nginx -o yaml
[root@k8s-m ~]# kubectl exec -it nginx-ingress-controller-5f947cc79f-86cvc -n ingress-nginx -- cat /etc/nginx/nginx.conf | grep client_header_buffer_size
trueclient_header_buffer_size 4k;

修改nginx-controller的yml文件nginx-ingress-daemonset.yaml启动参数如下:

1
2
3
4
5
6
7
8
9
10
spec:
containers:
- args:
- /nginx-ingress-controller
- --default-backend-service=$(POD_NAMESPACE)/default-http-backend
- --configmap=$(POD_NAMESPACE)/nginx-configuration //例如
- --tcp-services-configmap=$(POD_NAMESPACE)/tcp-services
- --udp-services-configmap=$(POD_NAMESPACE)/udp-services
- --publish-service=$(POD_NAMESPACE)/ingress-nginx
- --annotations-prefix=nginx.ingress.kubernetes.io

  • 如需要生效重启nginx-ingress-controller pod *

    二、使用Annotations

    如果只想自定义特定Ingress资源的配置,可以使用Annotations。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    apiVersion: extensions/v1beta1
    kind: Ingress
    metadata:
    name: cafe-ingress-with-annotations
    annotations:
    nginx.org/proxy-connect-timeout: "30s"
    nginx.org/proxy-read-timeout: "20s"
    nginx.org/client-max-body-size: "4m"
    spec:
    rules:
    - host: cafe.example.com
    http:
    paths:
    - path: /tea
    backend:
    serviceName: tea-svc
    servicePort: 80
    - path: /coffee
    backend:
    serviceName: coffee-svc
    servicePort: 80

Annotations配置优先于ConfigMap
https://github.com/nginxinc/kubernetes-ingress/tree/master/examples/customization
https://github.com/nginxinc/kubernetes-ingress/tree/master/examples/customization

限速

Annotationsingress.kubernetes.io/limit-connectionsingress.kubernetes.io/limit-rps定义可由单个客户端IP地址打开的连接的限制。这可用于缓解DDoS攻击

1
2
3
4
5
nginx.ingress.kubernetes.io/limit-connections:单个IP地址允许的并发连接数。

nginx.ingress.kubernetes.io/limit-rps:每秒可从给定IP接受的连接数。

如果在单个Ingress规则中指定两个Annotations,`limit-rps`则优先。