Docker:从容器内部连接到 localhost:port Refused

Bai*_*nim 1 connection containers docker

我正在尝试确保不同容器与使用端口8040的本地主机地址(127.0.0.1)之间的连接。(我的 Web 应用程序容器使用此端口运行。)

 root@a70b20fbda00:~# curl -v http://127.0.0.1
 * Rebuilt URL to: http://127.0.0.1/
 * Hostname was NOT found in DNS cache
 *   Trying 127.0.0.1...
 * connect to 127.0.0.1 port 80 failed: Connection refused
 * Failed to connect to 127.0.0.1 port 80: Connection refused
 * Closing connection 0
 curl: (7) Failed to connect to 127.0.0.1 port 80: Connection refused
Run Code Online (Sandbox Code Playgroud)

这是我想从容器内部连接到 localhost 时得到的结果

root@a70b20fbda00:~# curl -v http://127.0.0.1:8040
* Rebuilt URL to: http://127.0.0.1:8040/
* Hostname was NOT found in DNS cache
*   Trying 127.0.0.1...
* connect to 127.0.0.1 port 8040 failed: Connection refused
* Failed to connect to 127.0.0.1 port 8040: Connection refused
* Closing connection 0
curl: (7) Failed to connect to 127.0.0.1 port 8040: Connection refused
Run Code Online (Sandbox Code Playgroud)

关于每个容器中的iptables:

 root@a70b20fbda00:~# iptables
 bash: iptables: command not found
Run Code Online (Sandbox Code Playgroud)

容器之间的连接良好

root@635114ca18b7:~# ping 172.17.0.1
PING 172.17.0.1 (172.17.0.1) 56(84) bytes of data.
64 bytes from 172.17.0.1: icmp_seq=1 ttl=64 time=0.061 ms
64 bytes from 172.17.0.1: icmp_seq=2 ttl=64 time=0.253 ms
--- 172.17.0.1 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1002ms
root@635114ca18b7:~# ping 127.0.0.1
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.080 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.100 ms
--- 127.0.0.1 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
root@635114ca18b7:~# ping 172.17.0.3
PING 172.17.0.3 (172.17.0.3) 56(84) bytes of data.
64 bytes from 172.17.0.3: icmp_seq=1 ttl=64 time=0.149 ms
64 bytes from 172.17.0.3: icmp_seq=2 ttl=64 time=0.180 ms
--- 172.17.0.3 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 0.149/0.164/0.180/0.020 ms
Run Code Online (Sandbox Code Playgroud)

ping 127.0.0.1:8040

root@635114ca18b7:~# ping 127.0.01:8040
ping: unknown host 127.0.0.1:8040
Run Code Online (Sandbox Code Playgroud)

在这种情况下我需要做什么?

所以全局镜像有两个容器,

  • 第一个容器包含一个tomcat 服务器,用于部署我的Web 应用程序,它完美地运行。
  • 第二个是需要连接到 Web 应用程序 URL 的容器。http://127.0.0.1:8040/my_app

kak*_*ali 5

您将不得不使用docker run --network host IMAGE:TAG来实现所需的连接

进一步阅读这里

例子:-

docker run --network host --name CONTAINER1 IMAGE:tag

docker run --network host --name CONTAINER2 IMAGE:tag
Run Code Online (Sandbox Code Playgroud)

在容器内 - CONTAINER2 您将能够以主机 CONTAINER1 的身份访问其他容器

要访问该服务,您必须执行 CONTAINER: