docker React-Nodejs应用程序前端未加载停靠组合

lx0bsm1f  于 2022-12-11  发布在  Docker
关注(0)|答案(1)|浏览(135)

我有一个react nodejs应用程序,它在本地运行很好,但当我停靠它并运行停靠组合起来,前端网页从来没有加载和后端运行预期。我不知道我的配置哪里得到错误的前端,我会感谢您的帮助!
我有一个用于前端的dockerfile(react)和一个用于后端的dockerfile(nodejs)。我还有一个docker-compose.yml文件。文件结构如下所示:

--api(dir for backend)
 --dockerfile
--my-app(dir for frontend)
 --dockerfile
--dockercompose.yml

我的前端docker文件如下:

FROM node:10
WORKDIR /usr/src/app/my-app
COPY . .
RUN npm install && npm run build
EXPOSE 3001

CMD ["npm", "start"]

我的后端dockerfile如下:

FROM node:10
WORKDIR /root/
COPY ./package*.json ./api/
RUN cd api && npm install
COPY ./server.js ./api/
COPY ./tracing.js ./api/
EXPOSE 3080

CMD ["node", "--require",  "./api/tracing.js",  "./api/server.js"]

我的docker-compose文件如下:

version: '3'
services:
  app-backend:
    build: ./api
    container_name: app-backend
    ports:
        - "3080:3080"

  app-frontend:
    depends_on:
      - app-backend
    build: ./my-app
    container_name: app-frontend
    ports:
        - "3001:3001"
    tty: true

这是我的前端package.json的样子:

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "bootstrap": "^4.5.0",
    "react": "^16.13.1",
    "react-bootstrap": "^1.0.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "proxy": "http://app-backend:3080",
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

docker-compose up后,我在CLI中看到类似下面的内容,我不知道为什么它会显示端口3000,我实际上将前端端口设置为3001。我在浏览器中尝试了3000和3001,但都不起作用。x1c 0d1x

c0vxltue

c0vxltue1#

您可以通过编辑server.js来更改nodejs应用程序侦听的端口,以便在其express调用中引用不同的端口。
然而,将docker指向被监听的实际端口,然后将其重新Map到主机上所需的端口,这要容易得多。假设nodejs正在监听:3000,而您希望在主机上的:3001上访问它,这是正确的compose.yml语法:

app-frontend:
    depends_on:
      - app-backend
    build: ./my-app
    container_name: app-frontend
    ports:
        - "3001:3000"
    tty: true

相关问题