简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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