after creating docker containers with docker compose file (below), I call
$ docker run myApp
However, I get
Error: getaddrinfo ENOTFOUND main_db
this only happens when both server and postgresql are in docker containers (I am able to connect to postgresql on localhost)
I'm running a NestJS app using TypeOrm to connect to a postgresql server
inside the app.module.ts
where it boots up the connection my config should match my docker postgresql config. the host
points to the container I created on docker main_db
and I declared this as a dependency of my server, the main
service. Everything should be on the same network webnet
.:
TypeOrmModule.forRoot({
type: 'postgres',
host: 'main_db',
port: +process.env.POSTGRES_PORT,
username: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DB,
autoLoadEntities: true,
synchronize: true,
logging: dbLogging,
}),
docker-compose.yml
version: '3.7'
services:
main:
container_name: main
build:
context: .
target: development
volumes:
- .:/usr/src/app
- /usr/src/app/node_modules
ports:
- ${SERVER_PORT}:${SERVER_PORT}
- 9229:9229
command: npm run start:dev
env_file:
- .env
networks:
- webnet
depends_on:
- main_db
main_db:
container_name: main_db
image: postgres:12
restart: always
networks:
- webnet
environment:
POSTGRES_DB: ${POSTGRES_DB}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_USER: ${POSTGRES_USER}
PG_DATA: /var/lib/postgresql/data
ports:
- '${POSTGRES_PORT}:${POSTGRES_PORT}'
volumes:
- pgdata:/var/lib/postgresql/data
networks:
webnet:
volumes:
pgdata:
.env
file
POSTGRES_PORT=5432
POSTGRES_USER=test
POSTGRES_PASSWORD=test
POSTGRES_DB=test
SERVER_PORT=3001
When creating a Dockerfile
and a docker-compose.yml
file and you call docker run myApp
for the app defined inside of the Dockerfile
instead of calling docker-compose up
, you will see the app running; however, it will not start the containers defined in the docker-compose
file. In the case of the NestJS server, it was running the server, but could not find the container with the database, since this container was not being spun up. Although the distinction between the app setup in the Dockerfile
and the definition of the containers in the docker-compose.yml
was clear, I didn't realize that the docker
command didn't reference the docker-compose.yml
. Thus, posting here in case anyone else has a similar confusion.