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 ?