-2

我有一个reactjs前端应用程序和一个简单的python flask. 我正在使用 adocker-compose.yml来启动两个容器,就像这样:

version: "3.2"

services:

  frontend:
    build: .
    environment:
      CHOKIDAR_USEPOLLING: "true"
    ports:
      - 80:80
    links:
      - "backend:backend"
    depends_on:
      - backend 

  backend: 
    build: ./api
    # volumes:
      # - ./api:/usr/src/app
    environment:
      # CHOKIDAR_USEPOLLING: "true"
      FLASK_APP: /usr/src/app/server.py
      FLASK_DEBUG: 1
    ports: 
      - 8083:8083

我已经使用links了,因此该服务可以使用如下方式与frontend服务交谈:backendaxios

axio.get("http://backend:8083/monitors").then(res => {
      this.setState({
        status: res.data
      });
    });

我曾经docker-compose up --build -d构建和启动两个容器,它们启动时没有任何问题并且运行良好。

但是现在frontend不能说话了backend

我正在使用AWSec2 实例。当页面加载时,我尝试查看任何控制台错误并收到此错误:

VM167:1 GET http://backend:8083/monitors net::ERR_NAME_NOT_RESOLVED

有人可以帮帮我吗?

backend服务已启动并正在运行。

4

1 回答 1

-1

您可以使用 nginx 作为反向代理

撰写文件

version: "3.2"

services:
  frontend:
    build: .
    environment:
      CHOKIDAR_USEPOLLING: "true"
    depends_on:
      - backend 

  backend: 
    build: ./api
    # volumes:
      # - ./api:/usr/src/app
    environment:
      # CHOKIDAR_USEPOLLING: "true"
      FLASK_APP: /usr/src/app/server.py
      FLASK_DEBUG: 1

  proxy: 
    image: nginx
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/example.conf
    ports: 
      - 80:80

最小的 nginx 配置(nginx.conf):

server {
    server_name example.com;
    server_tokens off;

    location / {
        proxy_pass http://frontend:80;
    }
}

server {
    server_name api.example.com;
    server_tokens off;

    location / {
        proxy_pass http://backend:8083;
    }
}

请求命中 nginx 容器并根据域路由到正确的容器。

要使用 example.com 和 api.example.com,您需要编辑 hosts 文件:

Linux:/etc/hosts
Windows:c:\windows\system32\drivers\etc\hosts
Mac:/private/etc/hosts

127.0.0.1 example.com api.example.com
于 2021-02-11T08:49:45.707 回答