2

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?

2 Answers 2

12

Try "host": "db" instead of localhost. Docker-compose uses the service name as its DNS entry

Sign up to request clarification or add additional context in comments.

1 Comment

So it seems that I had to change the host to db as you said, and also I've changed the db to mariadb and everything is fine now ;)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.