'Node.js with MySQL docker container network setup

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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeremy