首页 > 解决方案 > 如何从 docker 容器到达机器端口

问题描述

我有docker运行node应用程序的容器。node在 7000 端口的机器级别上运行的其他应用程序。docker我的目标是machine使用axios.

docker 开始于:

docker run -p 3000:3000 -p 4000:4000 -i -t gepick_env:latest -d --network='host'

docker 片段上的客户端:

 ....
 axios.post(                                                                                                           
    'http://localhost:7000/predict',                                                                                    
    matchesToPredict                                                                                                    
  ).then(res => {...})
...  

我尝试test使用本地的 curl。

➜  gepick-devenv git:(master) ✗ curl http://localhost:7000/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /</pre>
</body>
</html>

试过做同样的事情docker

首先我docker通过以下命令登录:

docker exec -i -t 6c9036c76463 /bin/bash

并尝试:

[root@6c9036c76463 /]# curl http://localhost:7000/
curl: (7) Failed to connect to ::1: Network is unreachable

`

标签: docker

解决方案


By default, docker creates and uses network 172.17.0.0/16 for containers.

In this network the address 172.17.0.1 is assigned to the host where docker daemon is running (i.e: your machine).

So pointing to that address should work:

 curl http://172.18.0.1:7000/

You can get what is the gateway address of a specific container by executing:

docker inspect --format "{{range .NetworkSettings.Networks}}{{ .Gateway }}{{end}}" \
   <container-name>

推荐阅读