1

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.

1 Answers1

0

You are trying to connect to localhost

By using localhost it will try to reach to container's localhost

You should use instead the name of the service db

Since compose will create by default a bridge network. Your API container will be able to resolve the database container IP by the name of the service

Change

 host: 'localhost',
 port: 3306,
 ...

To

 host: 'db',
 port: 3306,
 ...
Tolis Gerodimos
  • 3,782
  • 2
  • 7
  • 14