如何配置Apollo Server实现Apollo Studio连接探索Dgraph
问题根因
直接填写Dgraph原生服务地址无法连通Apollo Studio和服务本身可用性无关,核心是两个默认配置不匹配:
- Dgraph Alpha默认CORS规则没有放行Apollo Studio的源站,也没有正确响应浏览器跨域预检(OPTIONS)请求,所有请求会被浏览器安全策略拦截
- Dgraph原生GraphQL端点默认关闭了公网场景下的introspection查询支持,而Apollo Studio连通时首先会拉取全量Schema做introspection校验
不需要强制部署全量Apollo Server,根据你的使用场景选下面两种方案即可。
方案一:原生配置适配(无额外服务,适合纯调试场景)
只需要修改Dgraph启动参数即可,不需要写额外代码:
- 先本地校验Dgraph服务状态:执行
curl http://localhost:8080/health,确认返回alpha节点状态为正常 - 修改Dgraph Alpha的启动配置,如果是Docker Compose部署,在alpha服务的
environment段添加以下参数:
environment: - DGRAPH_ALPHA_GRAPHQL_CORS_ALLOWED_ORIGINS=https://studio.apollographql.com - DGRAPH_ALPHA_GRAPHQL_CORS_ALLOWED_METHODS=GET,POST,OPTIONS - DGRAPH_ALPHA_GRAPHQL_CORS_ALLOWED_HEADERS=Content-Type,Authorization - DGRAPH_ALPHA_GRAPHQL_INTROSPECTION=true
- 重启Alpha容器让配置生效:
docker compose restart alpha - 回到Apollo Studio连接页,端点地址填
http://localhost:8080/graphql,点击页面上的「Start tunnel」启动本地隧道(不要跳过这步,Apollo Studio的Web端需要隧道把本地端口映射到可访问的临时地址,避免本地环回地址拦截),等待隧道启动完成后即可连通。
注意:如果你的Dgraph部署在公网服务器上,不需要启动隧道,直接填写
http://<你的服务器IP>:8080/graphql即可,记得确认服务器防火墙放开8080端口的入站规则。
方案二:部署Apollo Server中转层(适合需要自定义逻辑的生产/扩展场景)
如果你需要加权限校验、自定义Resolver、请求日志等逻辑,再部署Apollo Server做中转:
- 初始化项目环境
mkdir dgraph-apollo-proxy && cd dgraph-apollo-proxy npm init -y npm install @apollo/server graphql @as-integrations/fastify node-fetch
- 在项目根目录新建
index.js,写入透传转发逻辑:
const { ApolloServer } = require('@apollo/server'); const { fastifyApollo } = require('@as-integrations/fastify'); const Fastify = require('fastify'); const fetch = require('node-fetch'); // 改成你自己的Dgraph GraphQL端点地址 const DGRAPH_ENDPOINT = 'http://localhost:8080/graphql'; async function startServer() { const apollo = new ApolloServer({ introspection: true, async executor({ request }) { // 所有请求直接透传到Dgraph,需要加自定义逻辑可以在这里扩展 const resp = await fetch(DGRAPH_ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(request) }); return resp.json(); } }); await apollo.start(); const app = Fastify(); await app.register(fastifyApollo(apollo), { cors: { origin: ['https://studio.apollographql.com'], methods: ['GET', 'POST', 'OPTIONS'], allowedHeaders: ['Content-Type', 'Authorization'], credentials: true } }); await app.listen({ port: 4000 }); console.log('Apollo proxy running at http://localhost:4000'); } startServer();
- 启动代理服务:
node index.js - 回到Apollo Studio连接页,端点地址填
http://localhost:4000,同样启动本地隧道后即可正常连通,所有在Studio发起的查询、变更操作都会自动透传到后端Dgraph。
避坑提示
- 不要直接把Dgraph 8080端口无鉴权暴露到公网,生产环境必须在中转层加Token校验、访问频率限制
- 如果连通时报introspection错误,先本地执行
curl -X POST -H "Content-Type: application/json" -d '{"query":"{__schema{types{name}}}"}' http://localhost:8080/graphql,确认Dgraph本身能正常响应introspection请求再排查Apollo侧配置
内容的提问来源于stack exchange,提问作者behnam-io
相关产品推荐
相关产品推荐

