连接多个docker容器docker-compose-front->api->solr

问题描述

我想连接多个 docker 容器。我有 3 项服务:

我可以创建后端来查询 solr 并在将 url 放入浏览器时显示结果。但是,我无法使用 fetch 从前端代码中使用该端点。我还可以查询一个后端端点,但它只是一个虚拟端点,返回“hello world” - 所以我怀疑问题出在 3 个容器之间的连接(因为后端连接到 solr,但前端不能连接在它上面)。

我的 docekr-compose.yml 文件

version: '3.8'

services:
    api-service:
        build: api
        volumes:
            - ./api/:/backend
        environment:
            - FLASK_ENV=development
            - FLASK_APP=app.py
        ports:
            - "5000:5000"
        networks:
            - solr
        depends_on:
            - solr
        links:
            - solr
    front:
        build: front
        volumes:
            - ./front:/frontend
            - node-modules:/frontend/node_modules
        environment:
            - NODE_ENV=development
        ports:
            - "3000:3000"
        depends_on:
            - api-service
        links:
            - api-service
            - solr
    solr:
        image: solr:8.5
        container_name: solr
        ports:
            - "8983:8983"
        networks:
            - solr
        command:
            - solr-precreate
            - gettingstarted
volumes:
    node-modules:

networks:
  solr:

用于连接 Solr 的 Flask 代码

BASE_PATH='http://solr:8983/solr/gettingstarted/select?q=%2A:%2A'
@app.route('/myquery',methods=['GET','POST'])
def my_query_solr():
    connection = urlopen("{}".format(BASE_PATH))
    response = simplejson.load(connection)

    return response

我的 js 代码命中 Flask 端点:

submitHandler = (e) => {
    e.preventDefault();
    fetch("http://localhost:5000/myquery/")
      .then(res => res.json())
      .then(
        (result) => {console.log(result["response"]["docs"])},(error) => {
          this.setState({
            isLoaded: true,error,});
        }
      )
    }

我尝试代替 localhost:5000/myquery 使用 api:5000/myquery 或 solr:5000/myquery,但都不起作用 - 当我检查浏览器中的元素时,我得到 ERR_NAME_NOT_RESOLVED 或 404。我在这里阅读了一些主题。我能够基于此修复我之前的问题(它在 api 和 solr 之间连接 - 我使用 docker-compose.yml 中的链接修复了它),但现在我正在通过前端使用它。

解决方法

正如 DavidMaze 所建议的,这归结为在 @app.route('/myquery') 中没有训练 / 并且在 fetch("http://localhost:5000/myquery/") 中有它。从 fetch 中移除训练 / 有帮助。