Python 在docker中为应用程序使用其他端口
我有一个Python应用程序,它使用Docker为项目和项目数据库创建容器。默认情况下,它使用端口80,如果我们想创建应用程序的多个实例,我可以显式提供端口号Python 在docker中为应用程序使用其他端口,python,docker,networking,port,Python,Docker,Networking,Port,我有一个Python应用程序,它使用Docker为项目和项目数据库创建容器。默认情况下,它使用端口80,如果我们想创建应用程序的多个实例,我可以显式提供端口号 # port 80 is already used, so, try another port $ bin/butler.py setup --port=82 但是,使用-port提供的端口信息也可能已被同一应用程序的另一个实例使用。因此,最好知道哪些端口已经用于应用程序,并选择不使用其中任何端口 我如何知道应用程序目前使用的端口?我想
# port 80 is already used, so, try another port
$ bin/butler.py setup --port=82
但是,使用-port提供的端口信息也可能已被同一应用程序的另一个实例使用。因此,最好知道哪些端口已经用于应用程序,并选择不使用其中任何端口
我如何知道应用程序目前使用的端口?我想在Python中执行这一点 您可以始终使用子流程模块,例如运行ps-elf | grep bin/butler.py,并使用正则表达式或简单的字符串操作解析输出,然后提取使用的端口。可能就是您需要的包。您可以使用并从那里获取侦听端口
[conn.laddr.port for conn in psutil.net_connections() if conn.status=='LISTEN']
我编写了一个解决方案,您可以从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
我得到错误ps:invalize选项-s用法:ps[-AaCcEefhjlMmrSTvwXx][O fmt |-O fmt][G gid[,gid…][-G grp[,grp…][-u[uid,uid…][-p pid[,pid…][-tty[-u user[,user…]]ps[-L]我的错-应该是ps-elf | grep bin/butler.py,将进行编辑。您正在使用linux吗?关于子流程模块的事情是,您可以运行您将在cmd中写入的任何内容,因此您只需更改命令ps-elf。。。docker ps-format{{.Ports}}您的答案是返回所有侦听连接还是只返回python脚本使用的连接?这是列出所有内容,您可以简单地将其更改为仅列出当前版本,因为您的答案不太容易回答问题。当OP特别要求其脚本使用的端口时,返回所有侦听端口。
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