从本地主机上另一个容器内的容器访问docker端口 [英] Access docker ports from a container inside another container at localhost

查看:182
本文介绍了从本地主机上另一个容器内的容器访问docker端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个设置,其中我使用docker-compose构建了2个dockers.

I have a setup where I build 2 dockers with docker-compose.

1个容器是一个Web应用程序.我可以通过端口 8080 访问它.另一个容器是ElasticSearch;可以通过端口 9200 进行访问.

1 container is a web application. I can access it with port 8080. Another container is ElasticSearch; it's accessible with port 9200.

这是我的 docker-compose.yml 文件的内容:

version: '3'
services:
  serverapplication:
    build: "serverapplication"
    entrypoint:
      - bash
      - -x
      - init.sh
    command: ["jdbcUrl=${jdbcUrl} dbUser=${dbUser} dbUserPassword=${dbUserPassword}"]
    ports:
      - "8080:8080"
      - "8443:8443"
      - "8787:8787"
  elasticsearch:
    build: "elasticsearch"
    environment:
      - discovery.type=single-node
    ports:
      - "9200:9200"
      - "9300:9300"

当我浏览到 http://localhost:8080/serverapplication 时,可以看到我的服务器应用程序.当我浏览到 http://localhost:9200/时,我可以看到ElasticSearch的默认页面.

When I browse to http://localhost:8080/serverapplication I can see my server application. When I browse to http://localhost:9200/ I can see the default page of ElasticSearch.

但是,当我尝试从服务器应用程序内部访问ElasticSearch时,出现连接被拒绝"的情况.似乎 9200 端口在服务器应用程序的本地主机上无法访问.

But when I try to access ElasticSearch from inside the serverapplication, I get a "connection refused". It seems that the 9200 port is unreachable at localhost for the server application.

我该如何解决?

推荐答案

使用localhost从来都不是安全的,因为localhost对您的主机系统,elasticsearch和服务器应用程序而言还有其他含义.您只能从主机的本地主机访问容器,因为您正在将容器端口映射到主机的端口上.

It's never safe to use localhost, since localhost means something else for your host system, for elasticsearch and for your server application. You're only able to access the containers from your host's localhost because you're mapping container ports onto your host's ports.

  1. 将它们放入同一网络
  2. 给容器起个名字
  3. 通过其容器名称访问elasticsearch,Docker会自动将其解析为您的Elasticsearch容器的当前IP.

代码:

version: '3'
services:
  serverapplication:
    container_name: serverapplication
    build: "serverapplication"
    entrypoint:
      - bash
      - -x
      - init.sh
    command: ["jdbcUrl=${jdbcUrl} dbUser=${dbUser} dbUserPassword=${dbUserPassword}"]
    ports:
      - "8080:8080"
      - "8443:8443"
      - "8787:8787"
    networks:
      - my-network

  elasticsearch:
    container_name: elasticsearch
    build: "elasticsearch"
    environment:
      - discovery.type=single-node
    ports:
      - "9200:9200"
      - "9300:9300"
    networks:
      - my-network

networks:
  my-network:
    driver: bridge

这篇关于从本地主机上另一个容器内的容器访问docker端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆