Docker容器本地主机访问问题

时间:2018-10-02 05:25:03

标签: docker networking

我有在虚拟机中运行的docker。我正在运行2个容器,如下所示(消除的噪音)。

  

[abc_dev @ abclocaldev〜] $ docker ps

declare
total_purchases number(7,2);
begin
   total_purchases :=20;
   case
      when (total_purchases>200) then dbms_output.put_line('high');
      when (total_purchases>100) and total_purchases<200) then 
      dbms_output.put_line('mid');
      when (total_purchases<100) then dbms_output.put_line('low');
   end 
end

存储库正在运行一个应用程序,可以从端口30081访问该应用程序。我可以从VM以及主机(VM上的端口转发)访问该应用程序。 happy_stallman 无法访问127.0.0.1:30081上的存储库,我收到连接被拒绝

有人知道发生了什么吗?

我想补充说, happy_stallman 能够访问Google以及Intranet上的其他应用。

1 个答案:

答案 0 :(得分:3)

默认情况下,docker容器在bridge网络上运行。当您尝试从容器内部访问127.0.0.1:8080时,您正在访问容器的8080端口。

为了演示,让我们尝试使用其IP地址访问另一个容器。启动简单服务器:

$ docker run -it -p 8080:8080 trinitronx/python-simplehttpserver
Serving HTTP on 0.0.0.0 port 8080 ...

然后切换到另一个终端并检查8080是否暴露给主机:

$ wget 127.0.0.1:8080
--2018-10-02 10:51:14--  http://127.0.0.1:8080/
Connecting to 127.0.0.1:8080... connected.
HTTP request sent, awaiting response... 200 OK
Length: 178 [text/html]
Saving to: <<index.html.5>>

index.html.5                               100%[=====================================================================================>]     178  --.-KB/s    in 0s

2018-10-02 10:51:14 (18.9 MB/s) - <<index.html.5>> saved [178/178]

容器提供了文件,可以正常工作。现在,让我们尝试使用另一个容器做同样的事情:

$ docker run -it alpine wget 127.0.0.1:8080
Connecting to 127.0.0.1:8080 (127.0.0.1:8080)
wget: can't connect to remote host (127.0.0.1): Connection refused

不起作用,因为这里127.0.0.1alpine的本地地址,而不是主机地址。

要获取容器IP,请使用以下命令:

$ docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' 4f1fe52be173
172.17.0.3

4f1fe52be173是容器名称。指定正确的IP后,该容器可以访问另一个容器端口:

$ docker run -it alpine wget 172.17.0.3:8080
Connecting to 172.17.0.3:8080 (172.17.0.3:8080)
index.html           100% |*******************************|   178   0:00:00 ETA

如果您使用的是docker-compose,则可以简化此操作:

$ cat docker-compose.yml
version: '3'
services:
  web:
    image: trinitronx/python-simplehttpserver
    ports:
      - "8080:8080"
  client:
    image: alpine
    command: wget web:8080
    depends_on:
      - web

$ docker-compose up
Creating soon_web_1 ... done
Creating soon_client_1 ... done
Attaching to soon_web_1, soon_client_1
web_1     | soon_client_1.soon_default - - [02/Oct/2018 05:59:16] "GET / HTTP/1.1" 200 -
client_1  | Connecting to web:8080 (172.20.0.2:8080)
client_1  | index.html           100% |*******************************|   178   0:00:00 ETA
client_1  |
soon_client_1 exited with code 0

如您所见,容器IP地址没有直接的规范。而是使用web:8080访问容器端口。

请注意,depends_on不会等到容器“就绪”。为了更好地控制,请阅读本指南:https://docs.docker.com/compose/startup-order/

相关问题