Files
Kubernetes/网关/Ingress/Ingress限制IP访问.md
offends 05791351c3
All checks were successful
continuous-integration/drone Build is passing
新增Ingress流量控制文档
2025-10-31 21:02:15 +08:00

80 lines
2.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

> 本文作者:丁辉
# Ingress限制IP访问
我们有时会遇到服务器请求过高疑似被攻击的情况这时候我们就需要限制不知名IP的请求访问本文记录如何配置全局 Ingress 配置限制某个IP访问的配置和验证过程。
## 修改 Ingress 配置
我们需要找到 Ingress 的配置文件并修改它
```bash
kubectl get configmap -n ingress-nginx
```
修改
```bash
kubectl edit configmap ingress-nginx-controller -n ingress-nginx
```
添加如下内容
> 我们需要在 Nginx-Ingress 内使用 `http-snippet` 来配置限制。
>
> NGINX 控制器只识别官方支持的配置项,比如:
>
> - `http-snippet`
> - `server-snippet`
> - `location-snippet`
> - `use-forwarded-headers`
> - `allow-snippet-annotations`
> - 等等。
```yaml
data:
http-snippet: |
deny #需要限制的IP;
deny 192.168.100.100;
allow all;
```
**参数解释**
| 指令 | 含义 |
| :-----------------------: | :-----------------------------------------------: |
| `deny 192.168.100.100;` | 拒绝来自该 IP 的访问 |
| `allow 192.168.100.0/16;` | 允许来自该网段的访问 |
| `allow all;` | 允许所有其他请求(即没有被前面的 deny 拦住的 IP |
## 重启 NGINX Ingress Controller
> 资源类型是 `daemonset` 或 `deployment` 这就需要看安装时选择的参数来确定了,因为许多环境都不同。
```bash
kubectl rollout restart daemonset ingress-nginx-controller -n ingress-nginx
```
## 检查是否生效
## 验证方案
### 从被禁止的 IP 测试
假设你在某台机器(或 Pod上模拟访问
```
curl -I http://your-domain.com
```
如果 IP 在 `deny` 列表中,应该返回 `HTTP/1.1 403 Forbidden`
### 从其他 IP 测试
使用不同 IP 的机器再访问一次
```
curl -I http://your-domain.com
```
应能正常访问 `HTTP/1.1 200 OK`