Arefe
Arefe

Reputation: 12397

Use a different port for the app in docker

I have a Python app which creates containers for the project and the project database using Docker. By default, it uses port 80 and if we would like to create the multiple instances of the app, I can explicitly provide the port number,

# port 80 is already used, so, try another port
$ bin/butler.py setup --port=82

However, it also happens that the port info provided (using --port) is already used by another instance of the same app. So, it will be better to know which ports are already being used for the app and choose not to use any of them.

How do I know which ports the app use till now? I would like to execute that inside Python.

Upvotes: 0

Views: 133

Answers (3)

Arefe
Arefe

Reputation: 12397

I write a solution where you can get all the ports used by docker from the Python code,

def cmd_ports_info(self, args=None):

    cmd = "docker ps --format '{{.Ports}}'"

    try:
        cp = subprocess.run(cmd,
                            shell=True,
                            check=True,
                            stdout=subprocess.PIPE)
        cp = cp.stdout.decode("utf-8").strip()

        lines = str(cp).splitlines()
        ports = []

        for line in lines:

            items = line.split(",")

            for item in items:

                port = re.findall('\d+(?!.*->)', item)
                ports.extend(port)

        # create a unique list of ports utilized
        ports = list(set(ports))
        print(colored(f"List of ports utilized till now {ports}\n" + "Please, use another port to start the project", 'green',
                      attrs=['reverse', 'blink']))

    except Exception as e:
        print(f"Docker exec failed command {e}")
        return None

Upvotes: 0

user9303491
user9303491

Reputation:

psutil might be the package you need. You can use the net_connections and grab listen ports from there.

[conn.laddr.port for conn in psutil.net_connections() if conn.status=='LISTEN']
[8000,80,22,1298]

Upvotes: 0

ddor254
ddor254

Reputation: 1628

you can always use subprocess module, run ps -elf | grep bin/butler.py for example and parse the output with regex or simple string manipulation, then extract the used ports .

Upvotes: 1

Related Questions