teej2542
teej2542

Reputation: 608

Nodejs and React inside docker containers

I am trying to run Node/React project inside Docker containers. I have a NodeJS server for the API's and the client app. I also have concurrently installed and everything works fine when running npm run dev.

This issue is when I run the server and app via a docker-compose.yml file I get the following error from the client:

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)

Here is the 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

Server 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" ]

Client Dockerfile

FROM node:lts-slim

RUN mkdir -p /usr/src/app

WORKDIR /usr/src/app

EXPOSE 3000

CMD [ "npm", "start" ]

I am using "http-proxy-middleware": "^0.21.0" so my setupProxy.js is

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' }));
};

Upvotes: 1

Views: 491

Answers (1)

Aditya T
Aditya T

Reputation: 1723

You should use container_name instead of localhost

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

You can also check these details by inspecting your network using following command:-

docker inspect <network_name>

It will show all the connected containers to the network, also the host names created for those containers.

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

Upvotes: 3

Related Questions