从挂载了docker.sock的Docker容器中查找主机上的开放端口 [英] Find open ports on host from inside a docker container with `docker.sock` mounted

查看:116
本文介绍了从挂载了docker.sock的Docker容器中查找主机上的开放端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在致力于在gitlab中启用评论应用.为此,我需要为每个合并请求/分支部署一个应用程序.这意味着我需要找到可以部署到的开放端口.

I am currently working on enabling review apps in 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.

所以我正在寻找一种优雅的解决方案.

So I am looking for an elegant solution.

我当然可以总是向主机SSH来执行这样的脚本,但这似乎是一个非常丑陋的解决方案.

I could of course always ssh into the host to execute such a script, but that seems like a very ugly solution.

我想知道是否可以在Runner中装载其他任何东西,以允许在Runner中执行的脚本在主机上找到开放端口.

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.

推荐答案

如果这样做没有达到我认为的目的,请告诉我删除此答案:

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" ]

使用命令

docker build -t find_empty_port .

让我像脚本一样使用dockercontainer:

lets me use the dockercontainer just like the script:

docker run --rm --network host find_empty_port

这也可以在装有 docker.sock 的容器中进行.

which is also possible to do from within a container which has docker.sock mounted.

这篇关于从挂载了docker.sock的Docker容器中查找主机上的开放端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆