python修改nginx配置文件_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'))

成功!!!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值