Reputation: 479
I have a Node.js app (using the new NestJS) framework, running on port 3000. As the database I use MySQL via TypeORM. Locally it all works fine. I am having problems dockerizing it though.
My TypeORM config:
{
"type": "mysql",
"host": "localhost",
"port": 3306,
"username": "root",
"password": "root",
"database": "nest",
"entities": ["src/**/*.entity{.ts,.js}"],
"synchronize": true
}
My docker-compose.yml
is as follows:
version: "3"
services:
db:
image: mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: nest
MYSQL_USER: root
MYSQL_PASSWORD: root
networks:
- new
nest:
image: grimscythe/nest-sample
depends_on:
- db
ports:
- 3000:3000
networks:
- new
networks:
new:
I've been reading the docs on this particular scenario and all should work just fine.
Bash'ing into the MySQL container shows that the DB is running just fine. However the Node framework spits Unable to connect to the database...
. Am I missing something in the docker-compose.yml
file?
Upvotes: 2
Views: 4098
Reputation: 1578
I have just been through the same thing, writing it up for those that follow.
Your typeorm config host is specified as localhost, which is fine and required for local development where there is no docker container, but if you want to connect typeorm to the docker container use db ie. the name of the service on your docker-compose file.
One suggestion is to use "host": process.env.HOST ?? 'localhost'
after installing the dotenv
package so that you can use the HOST from an env file, else use localhost. Or create an array of connections, named for test / production / staging and load the approriatly named typeorm config, depending on the NODE_ENV at the time.
See Ben Awad Youtube video for a good example.
Upvotes: 0
Reputation: 1095
Try "host": "db"
instead of localhost. Docker-compose uses the service name as its DNS entry
Upvotes: 12