Nginx Proxy Manager (NPM) 是一个基于Nginx的图形化管理工具,可以简化反向代理、SSL证书管理和访问控制的配置过程。在分布式系统中,它可以作为服务发现和路由的核心组件。
NPM本身不包含服务发现功能,但可以通过以下方式集成:
方案一:与Consul/Etcd集成
# 使用Consul Template自动更新NPM配置
consul-template -template="template.ctmpl:/etc/nginx/conf.d/service.conf:nginx -s reload"
方案二:自定义脚本同步
# 示例:定期从服务注册中心同步服务列表
import requests
import yaml
def sync_services():
services = requests.get('http://service-registry/api/services').json()
config = generate_npm_config(services)
with open('/data/nginx-proxy-manager/letsencrypt/services.yaml', 'w') as f:
yaml.dump(config, f)
# 触发NPM重载
通过NPM API实现动态路由管理:
# 添加新路由的API调用示例
curl -X POST http://npm-api:81/api/proxy-hosts \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"domain_names": ["service.example.com"],
"forward_host": "service-instance-1",
"forward_port": 8080,
"ssl_forced": true,
"caching_enabled": true,
"block_exploits": true
}'
在NPM中配置多目标负载均衡:
# 生成的Nginx配置示例
upstream backend {
least_conn;
server service-instance-1:8080 max_fails=3 fail_timeout=30s;
server service-instance-2:8080 max_fails=3 fail_timeout=30s;
server service-instance-3:8080 backup;
}
# 通过权重分流实现金丝雀发布
upstream backend {
server service-v1:8080 weight=90;
server service-v2:8080 weight=10;
}
# 将生产流量镜像到测试环境
server {
listen 80;
server_name production.example.com;
location / {
mirror /mirror;
proxy_pass http://production-backend;
}
location = /mirror {
internal;
proxy_pass http://test-backend$request_uri;
}
}
# 使用Nginx的error_page实现简单断路器
server {
proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
proxy_next_upstream_tries 3;
proxy_next_upstream_timeout 10s;
error_page 502 503 504 =503 @circuit_breaker;
location @circuit_breaker {
return 503 "Service Temporarily Unavailable";
# 或 proxy_pass http://fallback-service;
}
}
日志分析:
性能监控:
# 启用Nginx状态模块
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
自动证书管理:
启用WAF规则集:
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
限制访问:
location /admin {
allow 10.0.0.0/8;
deny all;
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}
定期审计配置:
nginx -t # 测试配置语法
nginx -T # 查看完整配置
version: '3'
services:
app:
image: 'jc21/nginx-proxy-manager:latest'
ports:
- '80:80'
- '81:81'
- '443:443'
volumes:
- ./data:/data
- ./letsencrypt:/etc/letsencrypt
environment:
DB_SQLITE_FILE: "/data/database.sqlite"
DISABLE_IPV6: "true"
deploy:
resources:
limits:
cpus: '2'
memory: 1G
Nginx Proxy Manager为分布式系统提供了灵活的路由和服务发现能力,通过合理配置可以实现: - 动态服务注册与发现 - 智能流量路由 - 多种负载均衡策略 - 无缝的证书管理 - 完善的监控和安全防护
对于更复杂的场景,可以考虑结合Kong、Traefik等更专业的API网关解决方案。