我的docker-compose.yml
有两个容器:frontend
和server
。前端通过Apollo与服务器的API通信,并使用process.env.VUE_APP_GRAPHQL_HTTP
获取http端点。
在docker-compose.yml
我有:
environment:
HOST: 0.0.0.0
VUE_APP_GRAPHQL_HTTP: 'http://server:4000/graphql'
VUE_APP_GRAPHQL_WS: 'ws://server:4000/graphql'
对于使用NuxtJS的服务器端渲染,它非常适用。在客户端,虽然我收到一个错误:
OPTIONS http://server:4000/graphql net::ERR_NAME_NOT_RESOLVED
如果我在VUE_APP_GRAPHQL_HTTP: 'http://localhost:4000/graphql'
中设置docker-compose.yml
,它可以在客户端工作,但不能在服务器端渲染。我当时得到ECONNREFUSED
错误。
所以问题是:如何使用NuxtJS解析服务器和客户端API的路径?
我完整的docker-compose.yml
version: "3.7"
services:
frontend:
container_name: frontend
image: node
restart: unless-stopped
command: npm run docker
volumes:
- ./frontend:/usr/src/app
- ~/.ssh:/root/.ssh:ro
working_dir: /usr/src/app
ports:
- "3000:3000"
environment:
HOST: 0.0.0.0
VUE_APP_GRAPHQL_HTTP: 'http://server:4000/graphql'
VUE_APP_GRAPHQL_WS: 'ws://server:4000/graphql'
depends_on:
- server
networks:
- app
server:
container_name: server
image: node
restart: unless-stopped
command: npm run docker
volumes:
- ./server:/usr/src/app
- ~/.ssh:/root/.ssh:ro
working_dir: /usr/src/app
ports:
- "4000:4000"
depends_on:
- database
environment:
PORT: 4000
DATABASE_URL: mongodb://database:27017
networks:
- app
database:
container_name: database
image: mongo
volumes:
- ./data:/data/db
ports:
- "27017:27017"
networks:
- app
networks:
app:
可能不是最好的方法,但我用服务器和前端的特殊规则解决了它。
在apollo config nuxt.config.js
中加载js文件
clientConfigs: {
default: '~/plugins/apollo.js',
},
插件/ apollo.js:
export default function(context) {
let httpEndpoint = process.env.APOLLO_SERVER_HTTP || 'http://localhost:4000/graphql';
let wsEndpoint = process.env.APOLLO_SERVER_WS || 'ws://localhost:4000/graphql';
if (process.client) {
httpEndpoint = process.env.APOLLO_CLIENT_HTTP || 'http://localhost:4000/graphql';
wsEndpoint = process.env.APOLLO_CLIENT_WS || 'ws://localhost:4000/graphql';
}
return {
httpEndpoint,
httpLinkOptions: {
credentials: 'same-origin',
},
wsEndpoint,
};
}
通过docker-compose传递变量:
environment:
HOST: 0.0.0.0
APOLLO_SERVER_HTTP: 'http://server:4000/graphql'
APOLLO_CLIENT_HTTP: 'http://localhost:4000/graphql'
APOLLO_SERVER_WS: 'ws://server:4000/graphql'
APOLLO_CLIENT_WS: 'ws://localhost:4000/graphql'