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

风流意气都作罢 提交于 2021-01-29 06:50:48

问题


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.

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

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.


回答1:


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:

docker run --rm --network host find_empty_port

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



来源:https://stackoverflow.com/questions/64902021/find-open-ports-on-host-from-inside-a-docker-container-with-docker-sock-mounte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!