I have a distributed application (YARN), which runs a WebApp.
This application use a default port to start (8008), before I start I need to check if port is in use.
A container may run in the same virtual machine, hence port may be in use. (Max I have 4 containers in WebApp).
I created the following code which seem to work, but want to see if there are some clean ups/improvements suggested.
def port_in_use(port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex(('127.0.0.1', port)) if result == 0: return True else: return False def start_dashboard(): base_port = os.getenv('DASHBOARD_PORT_ENV_VAR', 8008) scan_ports = True attempts = 0 max_attempts = 10 while(scan_ports and attempts <= max_attempts): if port_in_use(base_port): base_port += 1 attempts += 1 else: scan_ports = False if attempts == max_attempts: raise IOError('Port in use') dashboard.configure(port=base_port) dashboard.launch()