zookeeper 动态管理nginx配置
假设我们有一个场景,所有服务器共享同一份配置文件,我们肯定不可能单独手动维护每台服务器,这时可以利用zookeeper的配置管理功能。
环境:python + nginx + zookeeper
目的:当zookeeper中的配置文件发生变化时nginx自动拉取最新配置文件并应用到本地,最终重启服务器:
一。搭建zookeeper集群:
步骤略,请参考:http://zookeeper.apache.org/doc/r3.4.13/zookeeperStarted.html
请确保zookeeper集群为健康状态:
二。安装nginx
yum install nginx -y
启动nginx: systemctl start nginx
三。编写python zookeeper 客户端:
目的:定期连接zookeeper集群,检测配置文件发生变化:
from kazoo.client import KazooClient import time zk=KazooClient(hosts='192.168.85.137:2181') zk.start() Version=None while True: @zk.DataWatch("/nginx") def watch_node(data, stat): global Version if Version == None: Version=stat if Version != stat: Version = stat nginx_file=str(data,encoding='utf-8') print("配置已改变!!!!!") f=open('nginx.conf','w',encoding='utf-8') f.write(nginx_file) f.flush() f.close() import os Path=os.path.dirname(os.path.abspath(__file__)) os.system('cp -f %s/nginx.conf /etc/nginx/nginx.conf && systemctl restart nginx.service'%Path) #替换nginx配置文件,然后重启服务,注意,这这里只是写了一个大体框架,生产环境一定不要直接重启,可以写一些判断,至少应该先确保配置文件没有错误再重启nginx time.sleep(3)
测试:修改zookeeper中的nginx配置,看客户端是否能拉去配置文件:
from kazoo.client import KazooClient import time zk=KazooClient(hosts='192.168.85.137:2181') zk.start() nginx_config=""" user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; include /etc/nginx/conf.d/*.conf; server { listen 5555 default_server; index index.php index.html; server_name _; root /usr/share/nginx/html; include /etc/nginx/default.d/*.conf; location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; #fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_param PATH_INFO $fastcgi_path_info; include fastcgi_params; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } } """ zk.set('/nginx',bytes(nginx_config,encoding='utf-8'))
成功!!!
posted on 2019-03-18 16:02 it_man_xiangge 阅读(2627) 评论(0) 编辑 收藏 举报