An explanation of how to automatically generate Docker Nginx reverse proxy configuration using Python

Source: Internet
Author: User
Tags nginx reverse proxy docker ps

Because in the test environment with Docker deployment of multiple applications, and their ports have the same, some are not the same, the number is more, in the use of the Jenkins version of the time, the poor configuration, so want to write a script, in the Docker container creation, stop, Automatically generate Nginx reverse proxy, then reload Nginx

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

The goal is clear, as long as you can hear Docker's container start/stop events, you can

On the Internet, we can use Docker events to listen to the Docker event, try it, find out the basics, and write a program in Python to listen to the Docker event.

Python

#!/usr/bin/python# coding:utf8import osimport jsonimport reimport subprocessdef Override (Path, text): If not OS.PATH.E Xists (path) and os.path.exists (path+ "_temp"): Os.rename (path+ "_temp", path) FW = open (path+ "_temp", ' WB ') FW.W Rite (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 (PAT  h): 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): F Ilename = "/var/lib/docker/containers/" + container + "/config.v2.json" config = read_jsonfile (filename) name = conf ig[' Name '].replace ("/", "") port = config[' config '] [' Exposedports '].keys () [0].replace ('/tcp ', ') IP = cmd ("Docker I Nspect-f ' {. Networksettings.ipaddress}} ' "+ name" # ip = config[' networksettings ' [' Networks '] [' Bridge '] [' IPAddress '] ret = {' n '        Ame ': 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 '} ' ") 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/loc    Al/openresty/nginx/html/vhost.html ', "<pre>" + hosts + "</pre>") 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 St Dout=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 it will not end if you disconnect SSH

The main is to generate a conf file, the file to be introduced in the nginx.conf, and then each time a container start/stop to generate this file, and then restart Nginx, I have the container name plus a domain name, combined into a subdomain, Then the corresponding mapping relationship generated an HTML file, through the browser can access the file, and then copy the corresponding code into the local hosts file, can be implemented through the domain name access to the application, of course, only when the development test will do so, but also enough.

Related Article

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.