如何在docker-compose中将Nuxt应用程序链接到API服务器

问题描述 投票:0回答:1

我的docker-compose.yml有两个容器:frontendserver。前端通过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:
javascript docker vue.js docker-compose nuxt
1个回答
0
投票

可能不是最好的方法,但我用服务器和前端的特殊规则解决了它。

在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'
© www.soinside.com 2019 - 2024. All rights reserved.