How to access host port from docker container

前端 未结 14 1541
南旧
南旧 2020-11-22 03:41

I have a docker container running jenkins. As part of the build process, I need to access a web server that is run locally on the host machine. Is there a way the host web s

14条回答
  •  终归单人心
    2020-11-22 04:00

    This is an old question and had many answers, but none of those fit well enough to my context. In my case, the containers are very lean and do not contain any of the networking tools necessary to extract the host's ip address from within the container.

    Also, usin the --net="host" approach is a very rough approach that is not applicable when one wants to have well isolated network configuration with several containers.

    So, my approach is to extract the hosts' address at the host's side, and then pass it to the container with --add-host parameter:

    $ docker run --add-host=docker-host:`ip addr show docker0 | grep -Po 'inet \K[\d.]+'` image_name
    

    or, save the host's IP address in an environment variable and use the variable later:

    $ DOCKERIP=`ip addr show docker0 | grep -Po 'inet \K[\d.]+'`
    $ docker run --add-host=docker-host:$DOCKERIP image_name
    

    And then the docker-host is added to the container's hosts file, and you can use it in your database connection strings or API URLs.

提交回复
热议问题