I’m building a full-stack application for a college assignment. I’m using a PostgreSQL database and NestJS with TypeORM. Throughout development, the database was dockerized and I used it without any problems. During that time, my API was running locally. Now I’m trying to dockerize the API as well, but I cannot get it to connect to the database. And worst of all, I can’t get it to log anything except for:
[Nest] 237 - 09/14/2024, 8:36:42 PM ERROR [ExceptionHandler]
api-1 | AggregateError:
api-1 | at internalConnectMultiple (node:net:1117:18)
api-1 | at afterConnectMultiple (node:net:1684:7)
I’ve tried different things to make it log more verbosely, but i couldn’t get it to. Just those 4 lines.
This is my docker compose file
services:
client:
...
api:
build:
context: .
dockerfile: ./apps/api/api.Dockerfile
environment:
JWT_SECRET: ...
GOOGLE_KEY: ...
DATABASE_NAME: rwa
DATABASE_USERNAME: postgres
DATABASE_PASSWORD: password
DATABASE_HOST: db
depends_on:
db:
condition: service_healthy
ports:
- '3000:3000'
db:
image: postgres
environment:
POSTGRES_PASSWORD: password
POSTGRES_DB: rwa
shm_size: 128mb
healthcheck:
test: ['CMD', 'pg_isready', '-U', 'postgres', '-d', 'rwa']
interval: 10s
timeout: 5s
retries: 5
ports:
- '5432:5432'
This is api.Dockerfile
FROM node:lts-alpine3.19
WORKDIR /usr/src/api
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD [ "npx", "nx", "serve", "api", "--host", "0.0.0.0"]
This is the part of the code where i connect to the db
@Module({
imports: [
...
TypeOrmModule.forRoot({
type: 'postgres',
host: process.env.DATABASE_HOST ?? 'localhost',
port: 5432,
username: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
entities: [
...
],
synchronize: true,
}),
...
]
...
})
export class AppModule {}
I’ve tried setting up a Docker network, checked if process.env.DATABASE_HOST has no value, and tried using 'localhost'
instead of process.env.DATABASE_HOST ?? 'localhost'
. Nothing helped. I’ve used the docker exec command to ping the database from the API container, and it was successful, which is why I think this is a problem with TypeORM. After the API failed to connect from the container to the database, I tried connecting locally, and it was successful.
1