如何讓 docker container connect to docker host

Table of contents

No heading

No headings in the article.

今天讀到docker doc[1]講到如何使docker container可以跟在本機上run的一個簡單的server溝通,想說就來簡單跑跑看。

文件中給的範例很簡單,如下:


  1. Run the following command to start a simple HTTP server on port 8000.

    python -m http.server 8000

    If you have installed Python 2.x, run python -m SimpleHTTPServer 8000.

  2. Now, run a container, install curl, and try to connect to the host using the following commands:

     $ docker run --rm -it alpine sh
     # apk add curl
     # curl http://host.docker.internal:8000
     # exit
    

結果一跑發現docker不認得docker.internal

我的電腦環境是ubuntu22.04,並且安裝的是docker engine而非docker desktop。而關鍵就在docker.internal 這個傢伙。在舊版的docker engine是不支持docker.internal 的,想要這麼跑得安裝docker desktop才行。

但在docker18.03版本以後,docker engine是可以支援docker.internal 的,只不過需要在啟動container時多個flag [2]:

--add-host=host.docker.internal:host-gateway

有了這行指令,就可以成功在docker engine的container中與本機server溝通了!

[1]: https://docs.docker.com/desktop/networking/#use-cases-and-workarounds-for-all-platforms

[2]: https://medium.com/@TimvanBaarsen/how-to-connect-to-the-docker-host-from-inside-a-docker-container-112b4c71bc66