背景
k8s 集群对应的公网 slb ip 经常被人绑定域名,监控侧经常会收集到 502 相关状态码的异常告警,着手处理这种bad case
策略
1. 所有没有在ingress 配置过的域名要进行处理,即不是公司的、非法绑定到slb 上的域名要加上一条策略
2. NGINX Ingress Controller 设置未配置过的域名增加一条默认路由,指向一个固定的服务
方法
#cat Dockerfile
FROM nginx:latest #一个nginx镜像即可
ADD defalut.conf /opt/openresty/nginx/conf/vhost/ #拷贝一个nginx 自定义的配置文件进去
RUN mkdir /export/html #创建 404 图片放置的目录
COPY 404.jpeg /export/html/ #拷贝一张随意的404 图片
EXPOSE 80
CMD ["/opt/openresty/nginx/sbin/nginx","-g","daemon off;"]
#cat defalut.conf
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
location / {
root /user/share/nginx/html; #目录不用创建,且该目录也不用存在
index index.html index.htm;
error_page 404 /404.jpeg; #定义404 的方法
proxy_set_header HOST $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-FOR $proxy_add_x_forwarded_for;
}
location = /404.jpeg { #处理404 的方法
root /export/html;
}
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# cat default-dp.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: default-backend
namespace: default-backend
spec:
replicas: 1
selector:
matchLabels:
app: default-backend
template:
metadata:
labels:
app: default-backend
spec:
containers:
- name: default-backend
image: registry-vpc.cn-xxx.aliyuncs.com/xxx/nginx:default-server-v002
ports:
- containerPort: 80
# cat default-svc.yaml
apiVersion: v1
kind: Service
metadata:
name: default-backend
namespace: default-backend
spec:
selector:
app: default-backend
ports:
- protocol: TCP
port: 80
targetPort: 80
# cat default-ingress.yaml (nginx.ingress.kubernetes.io/default-backend注解,并结合*通配符来匹配所有未配置的域名)
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: example-ingress
namespace: default-backend
annotations:
nginx.ingress.kubernetes.io/default-backend: default-backend
spec:
rules:
- http:
paths:
- backend:
service:
name: default-backend
port:
number: 80
path: /
pathType: Prefix
# kubectl apply -f default-dp.yaml
# kubectl apply -f default-svc.yaml
# kubectl apply -f default-ingress.yaml
- 查看 ingress (* nginx.ingress.kubernetes.io/default-backend注解,并结合*通配符来匹配所有未配置的域名 )
# kubectl get ingress -n default-backend
NAME CLASS HOSTS ADDRESS PORTS AGE
example-ingress nginx * 172.16.4.41 80 3h37m
# 随意一个域名绑定到k8s 对外的slb 地址上,显示 404 的图片