在 docker 中为应用程序使用不同的端口

Use a different port for the app in docker

我有一个 Python 应用程序,它使用 Docker 为项目和项目数据库创建容器。默认情况下,它使用端口 80,如果我们想创建应用程序的多个实例,我可以明确提供端口号,

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

但是,提供的端口信息(使用 --port)也可能已被同一应用程序的另一个实例使用。因此,最好知道哪些端口已用于该应用程序并选择不使用其中任何一个。

我怎么知道应用程序目前使用了哪些端口?我想在 Python 内执行它。

您始终可以使用 subprocess 模块,例如 运行 ps -elf | grep bin/butler.py 并使用正则表达式或简单的字符串操作解析输出,然后提取使用的端口。

psutil might be the package you need. You can use the net_connections 并从那里获取监听端口。

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

我编写了一个解决方案,您可以从 Python 代码中获取 docker 使用的所有端口,

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