gpt4 book ai didi

node.js - Docker容器中的Node.js和React

转载 作者:行者123 更新时间:2023-12-02 18:50:48 25 4
gpt4 key购买 nike

我正在尝试在Docker容器中运行Node / React项目。我有一个用于API和客户端应用程序的NodeJS服务器。我还安装了concurrently,运行npm run dev时一切正常。

这个问题是当我通过docker-compose.yml文件运行服务器和应用程序时,我从客户端收到以下错误:
client | [HPM] Error occurred while trying to proxy request /api/current_user from localhost:3000 to http://localhost:5000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)
这是 docker-compose.yml

version: "3"
services:
frontend:
container_name: client
build:
context: ./client
dockerfile: Dockerfile
image: client
ports:
- "3000:3000"
volumes:
- ./client:/usr/src/app
networks:
- local
backend:
container_name: server
build:
context: ./
dockerfile: Dockerfile
image: server
ports:
- "5000:5000"
depends_on:
- frontend
volumes:
- ./:/usr/src/app
networks:
- local
networks:
local:
driver: bridge

服务器Dockerfile
FROM node:lts-slim

RUN mkdir -p /usr/src/app

WORKDIR /usr/src/app

EXPOSE 5000

# You can change this
CMD [ "npm", "run", "dev" ]

客户端Dockerfile
FROM node:lts-slim

RUN mkdir -p /usr/src/app

WORKDIR /usr/src/app

EXPOSE 3000

CMD [ "npm", "start" ]

我正在使用 "http-proxy-middleware": "^0.21.0",所以我的 setupProxy.js
const proxy = require('http-proxy-middleware');

module.exports = function(app) {
app.use(proxy('/auth/google', { target: 'http://localhost:5000' }));
app.use(proxy('/api/**', { target: 'http://localhost:5000' }));
};

最佳答案

您应该使用 container_name 而不是localhost

    app.use(proxy('/auth/google', { target: 'http://localhost:5000' }));
app.use(proxy('/api/**', { target: 'http://localhost:5000' }));

您还可以通过使用以下命令检查网络来检查这些详细信息:
docker inspect <network_name>

它将显示所有连接到网络的容器,以及为这些容器创建的主机名。

NOTE : Host names are created based on container_names otherwise based on service names.

关于node.js - Docker容器中的Node.js和React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60819747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com