Created
January 30, 2018 14:59
-
-
Save vladbabii/4423eaadb863a86f95ac75d31f23f6cf to your computer and use it in GitHub Desktop.
Configure haproxy automatically for docker open ports
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$list=@shell_exec('netstat -antepul | grep -i "listen" | grep "127.0.0.1:" | grep -i "docker-proxy"'); | |
$list=explode("\n",str_replace("\r","",$list)); | |
$ports=array(); | |
foreach($list as $k=>$v){ | |
$v=trim($v); | |
if(strlen($v)>0){ | |
while(stripos($v,' ')!==false){ | |
$v=str_replace(' ',' ',$v); | |
} | |
while(stripos($v,' ')!==false){ | |
$v=str_replace(' ',' ',$v); | |
} | |
$info=explode(" ",$v); | |
$port=false; | |
foreach($info as $k2=>$v2){ | |
if($port==false && stripos($v2,'127.0.0.1:')===0){ | |
$port=(int)substr($v2,strlen('127.0.0.1:')); | |
} | |
} | |
if($port!==false && is_numeric($port) && $port>0 && $port<=65300){ | |
$ports[$port]=true; | |
} | |
} | |
} | |
$ports=array_keys($ports); | |
$plist='Ports: '.implode(', ',$ports).PHP_EOL; | |
$data = file_get_contents('/etc/haproxy/haproxy.header.txt'); | |
$data.=PHP_EOL.PHP_EOL; | |
foreach($ports as $i=>$port){ | |
$hash=$port.'_'.md5($port); | |
$data.=' | |
frontend frontend_'.$hash.' | |
bind 10.9.8.7:'.$port.' | |
default_backend backend_'.$hash.' | |
backend backend_'.$hash.' | |
mode tcp | |
server local 127.0.0.1:'.$port.' check | |
'; | |
} | |
if(is_file('/etc/haproxy/haproxy.cfg')){ | |
$old=file_get_contents('/etc/haproxy/haproxy.cfg'); | |
}else{ | |
$old=''; | |
} | |
if(trim($old)!==trim($data)){ | |
echo $plist.PHP_EOL; | |
echo 'Writing and restarting...'.PHP_EOL; | |
file_put_contents('/etc/haproxy/haproxy.cfg',$data); | |
exec('systemctl restart haproxy'); | |
echo ' ...done'.PHP_EOL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment