首页 > 解决方案 > 从静态客户端访问 docker 容器的 IP 地址

问题描述

我有一个静态 Gatsby 应用程序,它需要来自另一个容器的 uri 来进行 Hasura GraphQL 连接。

问题

Gatsby 容器在 Hasura 之前完成了 docker 构建,因此 Gatsby 中的 URI 设置为undefined.

我怎样才能使 uri 是动态的,并在构建完成后更改为 Hasura 的实际容器 IP 地址?

我试过的

[0] https://docs.docker.com/compose/startup-order/

码头工人-compose.yml

version: '3.6'

services:
  database:
    image: postgres:12.2
    container_name: 'postgres-db'
    env_file:
      - database.env
    volumes:
      - ./schema.sql:/docker-entrypoint-initdb.d/1-schema.sql
      - ./seed.sql:/docker-entrypoint-initdb.d/2-seed.sql

  hasura:
    image: hasura/graphql-engine:v1.2.1
    restart: on-failure
    container_name: 'hasura'
    depends_on:
      - database
    ports:
      - '8180:8080'
    env_file:
      - hasura.env

  web:
    build: '.'
    image: 'webserver'
    container_name: 'nginx-webserver'
    restart: on-failure
    depends_on:
      - hasura
    ports:
      - '8080:80'
    volumes:
      - /app/node_modules
      - .:/app
    env_file:
      - webserver.env

webserver.env 文件

NODE_ENV=production
GATSBY_WEBPACK_PUBLICPATH=/
HASURA_ENDPOINT=http://hasura:8080/v1/graphql

需要 Hasura URI 的 GraphQL Apollo 客户端:

export const client = new ApolloClient({
  uri: process.env.HASURA_ENDPOINT,
  fetch,
});

标签: dockerdocker-composedockerfileapollo-clienthasura

解决方案


找到了解决方案。

我在错误地考虑容器网络关系。

客户端在连接时查看主机的 IP 地址,而不是容器的。

解释

  • Hasura 容器通过localhost:8180. 如果您查看 docker-compose 文件,port8180:8080的意思是“使 Hasura 的端口 8080 可访问 localhost 的端口 8180”。
  • gatsby 应用程序(nginx-webserver)应该指向localhost:8180,而不是hasura:8080.

我最终的 docker-compose.yml:

version: '3.6'

    services:
      database:
        image: postgres:12.2
        container_name: 'postgres-db'
        env_file:
          - database.env
        volumes:
          - ./schema.sql:/docker-entrypoint-initdb.d/1-schema.sql
          - ./seed.sql:/docker-entrypoint-initdb.d/2-seed.sql
    
      hasura:
        image: hasura/graphql-engine:v1.2.1
        restart: on-failure
        container_name: 'hasura'
        depends_on:
          - database
        ports:
          - '8180:8080'
        env_file:
          - hasura.env
    
      web:
        build: '.'
        image: 'nginx-webserver'
        container_name: 'web'
        restart: on-failure
        ports:
          - '8080:80'
        volumes:
          - .:/app
          - app/node_modules
        env_file:
          - webserver.env

ApolloClient 设置:

import ApolloClient from 'apollo-boost';
import fetch from 'isomorphic-fetch';

export const HASURA_ENDPOINT_URI =
  process.env.NODE_ENV === 'development'
    ? 'http://localhost:8090/v1/graphql'
    : 'http://localhost:8180/v1/graphql';

export const client = new ApolloClient({
  uri: HASURA_ENDPOINT_URI,
  fetch
});

推荐阅读