i have same problem with you and here is my solution:
You must define
DATABASE_URL: postgresql://${DB_USERNAME}:${DB_PASSWORD}@postgres-db:5432/${DB_DATABASE}
inside docker compose for backend service connect to the postgres db. here is my docker-compose file:
version: '4.0'
services:
db:
image: postgres
container_name: postgres
environment:
POSTGRES_USER: ${DB_USERNAME}
POSTGRES_PASSWORD: ${DB_PASSWORD}
POSTGRES_DB: ${DB_DATABASE}
ports:
- "5432:5432"
volumes:
- db_data:/var/lib/postgresql/data
backend:
build: .
container_name: backend
ports:
- "3000:3000"
environment:
DATABASE_URL: postgresql://${DB_USERNAME}:${DB_PASSWORD}@postgres-db:5432/${DB_DATABASE}
depends_on:
- db
volumes:
- .:/app
- /app/node_modules
volumes:
db_data:
then change the host(DB_HOST) in .env file equal to "db" (because you named postgres is "db" in docker-compose file)
PORT=3000
DB_HOST=db
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=123456
DB_DATABASE=auth
the typeORM config
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
type: 'postgres',
host: configService.get('DB_HOST'),
port: +configService.get('DB_PORT'),
username: configService.get('DB_USERNAME'),
password: configService.get('DB_PASSWORD'),
database: configService.get('DB_DATABASE'),
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true,
logging: true
}),
inject: [ConfigService],
}),