zookeeper 动态管理nginx配置
程序员文章站
2022-11-14 08:42:35
假设我们有一个场景,所有服务器共享同一份配置文件,我们肯定不可能单独手动维护每台服务器,这时可以利用zookeeper的配置管理功能。 环境:python + nginx + zookeeper 目的:当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'))
成功!!!
上一篇: python的字典
下一篇: python学习笔记(九)、模块