首页 > 解决方案 > 我在 Docker Compose 中得到了“ERR_EMPTY_RESPONSE”,即使两个单独的容器在单独运行时工作

问题描述

所以我有一个基本的前端和后端。后端依赖于一些环境变量,这是我的docker-compose.yml.

version: "3.9"
services:
  backend:
    env_file:
      - .env
    build:
      context: ./backend
    container_name: fastapi-api
    ports:
      - 80:80
  frontend:
    build:
      context: ./frontend
    container_name: vue-ui
    ports:
      - 8080:8080
    links:
      - backend

这给了我ERR_EMPTY_RESPONSE当我去的时候http://127.0.0.1:8080/,但是当我为我的前端和后端运行单独的 Dockerfile 时,这很顺利

我的前端

FROM node:lts-alpine

# install simple http server for serving static content
RUN npm install -g http-server

# make the 'frontend' folder the current working directory
WORKDIR /frontend

# copy both 'package.json' and 'package-lock.json' (if available)
COPY package*.json ./

# install project dependencies
RUN npm install

# copy project files and folders to the current working directory (i.e. 'app' folder)
COPY . .

# build app for production with minification
RUN npm run build

EXPOSE 8080
CMD [ "http-server", "dist" ]

我的后台

FROM tiangolo/uvicorn-gunicorn:python3.8

LABEL maintainer="Sebastian Ramirez <tiangolo@gmail.com>"

WORKDIR /backend

COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt

COPY . .
EXPOSE 80

这是我从跑步中看到的docker ps 在此处输入图像描述

这就是正在发生的事情,前端请求被发送到错误的地方 在此处输入图像描述

我想让它去这里 在此处输入图像描述

所以请求应该去端口 80 而不是端口 8000

这是我从开发工具中看到的 在此处输入图像描述

然而这是我的代码

axios
          .post(`http://127.0.0.1:80/city/`, {
            city_name: this.current_city
          })

额外的 0 来自哪里?

这就是我分别运行两个容器时发生的情况 在此处输入图像描述

标签: dockerdocker-composedockerfile

解决方案


通过查看docker ps输出,我猜您在配置中意外切换了后端和前端端口。前端有未映射的端口80,后端有未映射的端口8080

试试这个:

version: "3.9"
services:
  backend:
    env_file:
      - .env
    build:
      context: ./backend
    container_name: fastapi-api
    ports:
      - 8080:8080
  frontend:
    build:
      context: ./frontend
    container_name: vue-ui
    ports:
      - 80:80
    links:
      - backend

推荐阅读