Home > Enterprise >  Docker NodeJS app cant connect to postgres database
Docker NodeJS app cant connect to postgres database

Time:01-12

I am farely new to docker and docker-compose. I tried to spin up a few services using docker which contain of a nodejs (Nest.js) api, a postgres db and pgadmin. Without the API (nodejs) app beeing dockerized I could connect to the docker database containers, but now that I also have dockerized the node app, it is not connecting anymore and I am clueless why. Is there anything wrong with the way I have set it up?

Here is my docker-compose file

version: "3"
services:
  nftapi:
    env_file:
      - .env
    build:
      context: .
    ports:
      - '5000:5000'
    depends_on: 
      - postgres
    volumes: 
      - .:/app
      - /app/node_modules
    networks:
      - postgres
      
  postgres:
    container_name: postgres
    image: postgres:latest
    ports:
    - "5432:5432"
    volumes:
    - /data/postgres:/data/postgres
    env_file:
    - docker.env
    networks:
    - postgres
 
  pgadmin:
    links:
    - postgres:postgres
    container_name: pgadmin
    image: dpage/pgadmin4
    ports:
    - "8080:80"
    volumes:
    - /data/pgadmin:/root/.pgadmin
    env_file:
    - docker.env
    networks:
    - postgres
 
networks:
  postgres:
    driver: bridge

This is the nodejs app Dockerfile which builds successfully and in the logs I see the app is trying to connect to the databse but it cant (no specific error) just that it doesnt find the db.

# Image source
FROM node:14-alpine

# Docker working directory
WORKDIR /app

# Copying file into APP directory of docker
COPY ./package.json /app/

RUN apk update && \
    apk add git
# Then install the NPM module
RUN yarn install

# Copy current directory to APP folder
COPY . /app/

EXPOSE 5000
CMD ["npm", "run", "start:dev"]

I have 2 env files in my projecs root directory.

  1. .env
  2. docker.env

As mentioned above, when I remove the "nftapi" service from docker and run the nodejs up with a simple npm start it is connecting to the postgres container.

TypeOrmModule.forRoot({
      type: 'postgres',
      host: process.env.POSTGRES_HOST,
      port: Number(process.env.POSTGRES_PORT),
      username: process.env.POSTGRES_USER,
      password: process.env.POSTGRES_PASSWORD,
      database: process.env.POSTGRES_DB,
      synchronize:true,
      entities: ['dist/**/*.entity{.ts,.js}'],
    }),

The host from the .env file that is used in the typeorm module is localhost

CodePudding user response:

When using networks with docker-compose you should use the name of the service as you hostname.

so in your case the hostname should be postgres and not localhost

You can read more about at here: https://docs.docker.com/compose/networking/

  •  Tags:  
  • Related