How to use python to automatically generate dockernginx reverse proxy configuration

Source: Internet
Author: User
Tags subdomain name nginx reverse proxy docker ps
Because multiple applications are deployed with docker in the Test environment, and their ports are the same, some are different, and the number is large, it is difficult to configure jenkins versions, so I want to write a script to automatically generate an nginx Reverse proxy when the docker container is created or stopped, and then reloadnginx

Because multiple applications are deployed with docker in the Test environment, and their ports are the same, some are different, and the number is large, it is difficult to configure jenkins versions, so I want to write a script to automatically generate nginx Reverse proxy when the docker container is created or stopped, and then reload nginx

My principle is to be as simple as possible, lightweight, and with less memory usage

The target is clear. you only need to be able to monitor the docker container startup/stop events.

I checked it online and I can use docker events to listen to docker events. I tried it and found it was basically satisfactory. so I wrote a program in python to listen to docker events.

Python

#!/usr/bin/python# coding: utf8import osimport jsonimport reimport subprocessdef override(path, text):    if not os.path.exists(path) and os.path.exists(path+"_temp"):        os.rename(path+"_temp",path)    fw = open(path+"_temp", 'wb')    fw.write(text)    fw.close()    if os.path.exists(path):        os.remove(path)    os.rename(path+"_temp", path)def read(path):    try:        fr = open(path, "rb")    except IOError:        print "The file don't exist, Please double check!"        return    lines = fr.readlines()    ret = ''    for line in lines:        ret += line    return retdef read_jsonfile(path):    return json.loads(read(path))def cmd(command):    return os.popen(command).read()def get_name(container):    return cmd("docker inspect -f '{{.Name}}' " + container).replace("/", "").replace('\n', '')def get_ip(container):    return cmd("docker inspect -f '{{.NetworkSettings.IPAddress}}' " + container).replace('\n', '')def get_port(container):    return cmd("docker inspect -f '{{.Config.ExposedPorts}}' " + container).replace('/tcp:{}]', '').replace('map[', '').replace('\n', '')def get_info(container):    filename = "/var/lib/docker/containers/" + container + "/config.v2.json"    config = read_jsonfile(filename)    name = config['Name'].replace("/", "")    port = config['Config']['ExposedPorts'].keys()[0].replace('/tcp', '')    ip = cmd("docker inspect -f '{{.NetworkSettings.IPAddress}}' " + name)    # ip = config['NetworkSettings']['Networks']['bridge']['IPAddress']    ret = {'name': name, 'port': port, 'ip': ip}    return rettpl = """    server {        listen 80;        server_name $name.test.com;        location / {        proxy_set_header X-Real-IP $remote_addr;            proxy_set_header Host $http_host;            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;            proxy_pass http://$ip:$port;        }    }"""def generate_conf():    print "generate_conf"    out = cmd("docker ps | grep -v CONTAINER | awk '{print $1}'")    containers = out.split("\n")    servers = ''    hosts = ''    for con in containers:        if con != '':            name = get_name(con)            ip = get_ip(con)            port = get_port(con)            print ip, port            if len(port) >= 2:                servers += tpl.replace("$name", name).replace("$ip", ip).replace("$port", port)                hosts += "11.12.13.14 " + name + ".test.com\n"    override('/usr/local/openresty/nginx/conf/vhost.conf', servers)    override('/usr/local/openresty/nginx/html/vhost.html', "
" + hosts + "
")def reload_nginx(): print "reload nginx" cmd('nginx -s reload')def auto_reload(): generate_conf() reload_nginx()print " ==================== docker events ==================== "# auto_reload()proc = subprocess.Popen(["docker", "events"], # shell=True, # windows: true, linux: false stdout=subprocess.PIPE)while 1: out = proc.stdout.readline() event = re.sub('\(|\)', "", out).split(" ") if out.find('container stop') != -1: auto_reload() print ' container stop ' elif out.find('container start') != -1: auto_reload() print ' start container ' if out == '': print "out " break

Start command:

nohup ./docker.py > /dev/null 2>&1 &

The program will run in the background, and ssh disconnection will not end.

Generate a conf file in nginx. in conf, this file is generated every time a container starts/stops, and nginx is restarted. I add the container name to a domain name and combine it into a subdomain name, then, an html file is generated for the corresponding ing relationship. you can access this file through a browser, and then copy the corresponding code to the hosts file on the local machine. This allows you to access the application through a domain name, of course, this is only done during development and testing, but it is enough.

The above is a detailed description of how to use python to automatically generate the reverse proxy configuration method for docker nginx. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.