【问题标题】:Connect docker container from another container and from localhost从另一个容器和 localhost 连接 docker 容器
【发布时间】:2019-05-24 07:05:46
【问题描述】:

我有一个简单的 Web 应用程序,我将其配置为在 docker 容器中运行。配置是这样的

version: '3'
services:
  service-1:
    build: service-1
    restart: unless-stopped
    ports:
      - "8080:8080"
    networks:
      - uni

  service-1-postgres:
    restart: unless-stopped
    ports:
      - "5432:5432"
    image: "postgres:11.3"
    environment:
      POSTGRES_PASSWORD: root
    networks:
      - uni

networks:
  uni:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 192.168.0.1/24

我使用 192.168.0.1(网络子网)连接到另一个容器内的 postgres 容器。但现在我希望能够从 IDE 运行我的服务以加快开发速度,并在容器中运行 db。但是现在与 db 的连接失败了。如何配置我的 docker-compose 使其能够使用同一主机连接到网络内部和外部(来自 db)的我的 db 容器。

【问题讨论】:

    标签: docker docker-compose


    【解决方案1】:

    重要的是为此进行某种实际配置。 C PostgreSQL 客户端库支持标准的PGHOST 环境变量,这是一个不错的选择。

    在本地开发 IDE 设置中,您可以设置 PGHOST=localhost 或不设置。它将连接到 localhost(从主机的角度来看)端口 5432,并且主机上的端口 5432 是您为 PostgreSQL 容器设置的发布端口。

    相反,当您在 Docker 中运行它时,您可以将 PGHOST 设置为另一个容器的名称,前提是两个容器位于同一个非默认网络上。 Docker Compose 将自动为您创建一个非默认网络,您不需要显示手动网络配置。使用其服务块的名称作为主机名可以访问容器。

    version: '3'
    services:
      service-1:
        build: service-1
        restart: unless-stopped
        ports:
          - "8080:8080"
        environment:
          PGHOST: service-1-postgres
    
      service-1-postgres:
        # as above, less the networks: block
    

    【讨论】:

      猜你喜欢
      • 2019-02-24
      • 2020-03-01
      • 2017-10-15
      • 2020-01-30
      • 2016-01-29
      • 1970-01-01
      • 1970-01-01
      • 2019-03-17
      • 2019-09-04
      相关资源
      最近更新 更多