Skip to content

Instantly share code, notes, and snippets.

@MarshalW
Created November 4, 2022 03:03
Show Gist options
  • Save MarshalW/e919e693b94aa975b38b3c9dea154232 to your computer and use it in GitHub Desktop.
Save MarshalW/e919e693b94aa975b38b3c9dea154232 to your computer and use it in GitHub Desktop.
在 Dockerfile 中使用 localhost

在 Dockerfile 中使用 localhost

需要增加2点:

  • localhost 替换为 host.docker.internal
  • 执行时增加 --network="host",比如 docker build --network="host" -t test .

启动一个本地的 http server 做测试:

# http://localhost:8080
echo 'test' > index.html && npx http-server .

Dockfile:

FROM curlimages/curl
RUN curl http://host.docker.internal:8080

执行:

$ docker build --network="host" -t test .
[+] Building 0.2s (6/6) FINISHED                                                                                   
 => [internal] load build definition from Dockerfile                                                          0.0s
 => => transferring dockerfile: 35B                                                                           0.0s
 => [internal] load .dockerignore                                                                             0.0s
 => => transferring context: 2B                                                                               0.0s
 => [internal] load metadata for docker.io/curlimages/curl:latest                                             0.0s
 => [1/2] FROM docker.io/curlimages/curl                                                                      0.0s
 => CACHED [2/2] RUN curl http://host.docker.internal:8080                                                    0.0s
 => exporting to image                                                                                        0.0s
 => => exporting layers                                                                                       0.0s
 => => writing image sha256:edc6521f7cd23c47e3cbb2a2fe50b9f5db5829311b162ac92437e04154450301                  0.0s
 => => naming to docker.io/library/test 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment