Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python can reload the nginx config file faster than I can write a new one
#!/usr/bin/env python
import time
import psutil
import os
import signal
def reload_process(psname="nginx"):
pids = psutil.pids()
for pid in pids:
try:
if psutil.Process(pid).name == psname:
os.kill(pid,signal.SIGHUP)
except psutil.NoSuchProcess:
pass
def main():
reloads = 0
start_time = time.time()
end_time = start_time + 1
while time.time() <= end_time:
reload_process()
reloads += 1
print reloads, start_time, end_time
if __name__ == "__main__":
while 1:
main()
user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 768;
# multi_accept on;
}
http {
upstream myapp1 {
{{ range . }}
server localhost:{{ .Port }} weight={{ .Weight }};
{{ end }}
}
server {
listen 80 default_server;
root /var/www/html;
server_name _;
location / {
proxy_pass http://myapp1;
}
}
}
package main
import (
"github.com/samalba/dockerclient"
"math/rand"
"text/template"
"log"
"os"
)
type PortWeight struct {
Port int
Weight int
}
var templates = template.Must(template.ParseFiles("nginx.conf"))
func main() {
// Init the client
docker, _ := dockerclient.NewDockerClient("unix:///var/run/docker.sock", nil)
rand.Seed(42)
// Get only running containers
containers, err := docker.ListContainers(false, false, "")
if err != nil {
log.Fatal(err)
}
container_ports := make([]*PortWeight,0,0)
for _, c := range containers {
container_ports = append(container_ports,&PortWeight{Port: c.Ports[0].PublicPort, Weight: rand.Intn(5) + 1})
log.Println(c.Id, c.Names, c.Ports[0].PublicPort)
}
f, _ := os.Create("/etc/nginx/nginx.conf")
err = templates.ExecuteTemplate(f, "nginx.conf", container_ports)
f.Close()
}
@alexlovelltroy

This comment has been minimized.

Copy link
Owner Author

alexlovelltroy commented Nov 6, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.