docker - 从静态客户端访问 docker 容器的 IP 地址
问题描述
我有一个静态 Gatsby 应用程序,它需要来自另一个容器的 uri 来进行 Hasura GraphQL 连接。
问题
Gatsby 容器在 Hasura 之前完成了 docker 构建,因此 Gatsby 中的 URI 设置为undefined
.
我怎样才能使 uri 是动态的,并在构建完成后更改为 Hasura 的实际容器 IP 地址?
我试过的
- 添加一个强制 Gatsby 等到 Hasura 容器准备好,所以它会在 Gatsby 容器开始构建时拥有 IP
depends_on
。docker-compose.yml
但是根据 [0],它不能保证 Gatsby 会等到 Hasura 完成后才开始自己。 - 它建议添加一个自定义 bash 脚本来强制 Gatsby 容器等待。如果我要使用
wait-for-it.sh
,子命令应该是什么(等待完成后的命令)?
[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,
});
解决方案
找到了解决方案。
我在错误地考虑容器网络关系。
客户端在连接时查看主机的 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
});
推荐阅读
- python - 当我的脚本导入模块 pikepdf 和 pdfminer3 时,如何修复 pyinstaller 'no module named...' 错误?
- html - Flex item's auto margin cuts parent's padding
- javascript - 当 x 值与标签重合时,Chartjs 折线图会全部打乱
- java - Do I need to clean up Thread objects in Java?
- ionic-framework - ionic serve 无法正常工作 我该如何解决这个错误?
- java - 如何根据当前日期过滤记录?
- ios - iOS 13 中的 UITabBar 透明标签错误
- javascript - 我想计算 ID 在 Json 响应中出现的次数
- reactjs - 反应原生如何从可重用组件中获取变量
- task - 如何在 Synology 中创建用户定义的任务?