0

I have build a node application with MYSQL that works perfectly on my machine, but I want to use Docker. The application fails when trying to connect to the database in the container.

SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306

my mysql container works fine, I even tested it and accessed it through a database manager.

Below is my docker-compose.yml file:

version: '3'

services:
  db:
    image: mysql:8
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: qwer
      MYSQL_DATABASE: claudio2022
    ports:
      - "3307:3306"
    volumes:
      - C:\Users\breno\sqlfile:/docker-entrypoint-initdb.d

  app:
    build: .
    restart: always
    environment:
      NODE_ENV: production
      DB_HOST: db
      DB_USER: root
      DB_PASSWORD: qwer
      DB_NAME: claudio2022
      DB_PORT: 3306
    ports:
      - "4000:4000"
    depends_on:
      - db

volumes:
  db_data:

My .env file:

PORT=4000
MYSQL_HOST=db
MYSQL_DB=claudio2022
MYSQL_USER=root
MYSQL_PASSWORD=qwer
MYSQL_PORT=3306
JWT_SECRET_KEY=4321

and at last my Sequelize Instance file:

import { Sequelize } from 'sequelize';
import dotenv from 'dotenv';

dotenv.config();

export const db = new Sequelize(
    process.env.MYSQL_DB as string,
    process.env.MYSQL_USER as string,
    process.env.MYSQL_PASSWORD as string,
    {
        dialect: 'mysql',
        port: parseInt(process.env.MYSQL_PORT as string),
        // By default host is 'localhost'           
        host: process.env.MYSQL_HOST as string
    }
);

I really can't figure out why on my machine it runs perfectly but when I run it in docker it doesn't work. Ive tried following THIS ANSWER but its too different from MYSQL file. Does anyone have any suggestions? What Am i missing out ?

  • That looks like your environment-variable settings aren't being seen when the container is run. The overall structure seems to match [this answer](/a/70733585), for example, it doesn't seem like you intend to use `localhost`. Is there any possibility you're trying to connect to the database in the Dockerfile, maybe, or you're running the application a different way than the Compose file you show here? – David Maze Apr 13 '23 at 19:02
  • Ive tried changing the host: `process.env.MYSQL_HOST as string` to `host: '172.18.0.2'` and restarted the app, but it still gives me the same error: `ConnectionRefusedError [SequelizeConnectionRefusedError]: connect ECONNREFUSED 127.0.0.1:3306` `2023-04-13 21:58:56 errno: -111, 2023-04-13 21:58:56 code: 'ECONNREFUSED', 2023-04-13 21:58:56 syscall: 'connect', 2023-04-13 21:58:56 address: '127.0.0.1', 2023-04-13 21:58:56 port: 3306, 2023-04-13 21:58:56 fatal: true` – Breno Santin Apr 13 '23 at 20:02

0 Answers0