简体   繁体   English

从安装了`docker.sock`的docker容器内查找主机上的开放端口

[英]Find open ports on host from inside a docker container with `docker.sock` mounted

I am currently working on enabling review apps in gitlab.我目前正在 gitlab 中启用评论应用程序。 In order to do that I need to deploy an app for every merge request/ branch.为此,我需要为每个合并请求/分支部署一个应用程序。 Which means I need to find open ports where I can deploy to.这意味着我需要找到可以部署到的开放端口。

Usually this issue would be solved by the answers to this question .通常这个问题会通过这个问题的答案来解决 But as the Gitlab Runner is itself a docker container with docker.sock mounted, I can not simply execute a script on the host to find empty ports.但是由于 Gitlab Runner 本身就是一个挂载了docker.sock容器,我不能简单地在主机上执行脚本来查找空端口。

So I am looking for an elegant solution.所以我正在寻找一个优雅的解决方案。

I could of course always ssh into the host to execute such a script, but that seems like a very ugly solution.我当然可以总是通过 ssh 进入主机来执行这样的脚本,但这似乎是一个非常丑陋的解决方案。

I wonder whether I can mount anything else into the Runner to allow a script executed within the Runner to find open ports on the host.我想知道是否可以在 Runner 中安装其他任何东西,以允许在 Runner 中执行的脚本找到主机上的开放端口。

Please tell me to delete this answer if this does not do what I think it does:如果这不符合我的想法,请告诉我删除此答案:

find_empty_port.py

#!/usr/bin/env python

import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind(('', 0))
    print(s.getsockname()[1])

Dockerfile

FROM python:3.8

COPY find_empty_port.py find_empty_port.py

ENTRYPOINT [ "python", "find_empty_port.py" ]

using the command使用命令

docker build -t find_empty_port .

lets me use the dockercontainer just like the script:让我像脚本一样使用 dockercontainer:

docker run --rm --network host find_empty_port

which is also possible to do from within a container which has docker.sock mounted.这也可以在安装了docker.sock的容器内docker.sock

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM