'Sequelize ERRCONNREFUSED to mysql db in docker compose [duplicate]

When booting up my api/app/db in docker compose the api is unable to connect to the mysql container.

docker-compose.yml

version: "3.8"
services:
    web:
        build:
            context: ./frontend
            dockerfile: Dockerfile-dev
        container_name: vue-ui-v2
        volumes:
            - ./frontend:/usr/src/app/ui
            - /usr/src/app/ui/node_modules
        ports:
            - "8080:8080"
        depends_on:
            - api
    api:
        build:
            context: ./backend
            dockerfile: Dockerfile-dev
        ports:
            - "4000:4000"
        container_name: node-api-v2
        volumes:
            - ./backend:/usr/src/app/api
            - /usr/src/app/api/node_modules
        depends_on:
            - db
    db:
        image: mysql:8.0
        cap_add:
            - SYS_NICE
        restart: always
        environment:
            - MYSQL_DATABASE=thebooks
            - MYSQL_ROOT_PASSWORD=defaultPassword
        ports:
            - '3306:3306'
        volumes:
            - db:/var/lib/mysql
volumes:
  db:

docker file for api

FROM node:12

WORKDIR /usr/src/app/api

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 4000

CMD [ "npm", "run", "start" ]

And connect call from sequelize:

    const sequelize = new Sequelize('thebooks', 'root', 'defaultPassword', {
        host: 'localhost',
        port: 3306,
        dialect: 'mysql'
      });

I feel like there must be something simple i'm missing, but I've been scratching my head for hours trying to follow this: https://www.bezkoder.com/docker-compose-nodejs-mysql/ and failing for a few hours.



Sources

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

Source: Stack Overflow

Solution Source