'cannot dockerize react app: unable to connect to database

I am trying to dockerize a react app with postgres database.

I am new to docker, so I followed tutorials online to come up with Dockerfile and docker-compose as shown below.

Dockerfile

# pull the official base image
FROM node:13.12.0-alpine
# set working direction
WORKDIR /app
# add `/app/node_modules/.bin` to $PATH
EXPOSE 1338
ENV PATH /app/node_modules/.bin:$PATH
# install application dependencies
COPY package.json ./
COPY package-lock.json ./
RUN npm i
# add app
COPY . ./
# start app
CMD ["npm", "start"]

docker-compose.yml

version: '3.7'

services:

  sample:
    container_name: sample
    build:
      context: .
      dockerfile: ./Dockerfile
    volumes:
      - '.:/app'
      - '/app/node_modules'
    ports:
      - 1338:1338
    environment:
      - CHOKIDAR_USEPOLLING=true
      - ASPNETCORE_URLS=https://+:1338
      - ASPNETCORE_HTTPS_PORT=1338
    depends_on:
      - db
  
  db:
    container_name: db
    image: postgres:14-alpine
    restart: always
    ports:
      - "5432:5432"
    environment:
      POSTGRES_DB: ###
      POSTGRES_USER: ###
      POSTGRES_PASSWORD: ###
      # I hide these information for privacy purpose, but I am 100% sure I input these information correctly.
    volumes:
      - ./db-data/:/var/lib/postgresql/data/

  adminer:
    image: adminer
    restart: always
    ports:
      - 8080:8080

volumes:
  pgdata1:

so what happened is when I tried to run docker-compose up , I suppose the db part had no issue, since it wrote database system is ready to accept connections. However, the "sample" part ended up with an error:

Server wasn't able to start properly.
error Error: connect ECONNREFUSED 127.0.0.1:5432
 at TCPConnectWrap.afterConnect [as oncomplete]

which does not make much sense to me since the database is already up so there should not be any issue with connection at all.

Feel free to share your view, any idea would be appreciated. Thank you.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source