【问题标题】:How to access port of one container in other docker containers with localhost in the same network如何使用同一网络中的 localhost 访问其他 docker 容器中的一个容器的端口
【发布时间】:2019-04-09 03:44:17
【问题描述】:

我可以使用带有端口映射的 localhost 访问本地机器中的 docker 容器端口,但在其他容器中无法以类似的方式访问它。

我的 docker-compose 文件创建了一个具有 80:80 端口映射的 Ubuntu 和 Nginx 容器。当我尝试从 Ubuntu 访问 Nginx URL 时,端口拒绝连接。我可以使用容器名称访问端口,但不能使用 localhost。

.
├── Dockerfile
└── docker-compose.yml

docker-compose.yml 文件内容

version: '2'

services:
    web:
      image: nginx
      ports:
       - "80:80"
      links:
        - userver
      depends_on:
        - userver

    userver:
      build:
        context: .
        dockerfile: Dockerfile

Dockerfile 内容

FROM ubuntu

RUN apt-get update && apt-get install -y net-tools curl
CMD tail -f /dev/null
docker-practice $ docker ps
CONTAINER ID        IMAGE                     COMMAND                  CREATED             STATUS              PORTS                NAMES
c3f06dc519d8        nginx                     "nginx -g 'daemon of…"   4 hours ago         Up 10 minutes       0.0.0.0:80->80/tcp   docker-practice_web_1
40324fa76612        docker-practice_userver   "/bin/sh -c 'tail -f…"   4 hours ago         Up 10 minutes       80/tcp               docker-practice_userver_1

使用 localhost 从本地主机访问 Nginx URL

docker-practice $ curl http://localhost -I
HTTP/1.1 200 OK
Server: nginx/1.15.10
Date: Tue, 09 Apr 2019 03:35:46 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 26 Mar 2019 14:04:38 GMT
Connection: keep-alive
ETag: "5c9a3176-264"
Accept-Ranges: bytes

使用 localhost 从 Ubuntu 容器访问 Nginx URL

root@40324fa76612:/# curl http://localhost -I
curl: (7) Failed to connect to localhost port 80: Connection refused

使用容器名称从 Ubuntu 容器访问 Nginx URL

root@40324fa76612:/# curl http://docker-practice_web_1 -I
HTTP/1.1 200 OK
Server: nginx/1.15.10
Date: Tue, 09 Apr 2019 03:42:13 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 26 Mar 2019 14:04:38 GMT
Connection: keep-alive
ETag: "5c9a3176-264"
Accept-Ranges: bytes

我希望在 Ubuntu docker 容器中使用 localhost 访问端口,但该端口拒绝连接。

【问题讨论】:

  • 从 docker-compose (network) userver 可以通过端口 80 上的服务名称 web 引用 Nginx 容器:curl --head http://web
  • NB links 在 docker-compose 中已弃用:docs.docker.com/compose/compose-file/#links

标签: docker docker-compose dockerfile


【解决方案1】:

容器本身就像一台机器(计算机)。因此,如果您输入一个容器并调用“localhost”,那么 localhost 将指向该容器。容器的整个想法是“包含”它的环境。使用容器时尽量不要再使用 localhost。

使用容器名称或服务名称(在 docker-compose 网络中时)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多