I have a problem with connecting my node app container to MySQL database. When -compose up I keep getting error from container logs:
server-1 | Unable to connect to database ConnectionRefusedError [SequelizeConnectionRefusedError]: connect ECONNREFUSED 172.20.0.2:3306
Here is my db instance:
const { Sequelize } = require("sequelize");
require("dotenv").config();
const sequelize = new Sequelize("admin", "password", "table", {
host: "mysql2",
dialect: "mysql",
port: 3306,
});
module.exports = sequelize;
Docker compose file:
services:
server:
build:
context: .
ports:
- "3001:3001"
restart: always
depends_on:
- "mysql"
mysql:
image: mysql:8.0.0
container_name: mysql2
restart: always
environment:
MYSQL_USER: admin
MYSQL_ROOT_PASSWORD: password
ports:
- "3307:3306"
and Dockerfile:
Docker file:
FROM node:20-alpine
WORKDIR /server
COPY package.json .
RUN npm install --production
COPY . .
EXPOSE 3001
CMD ["node", "index.js"]
I tried creating just a MYSQL container and have been able to initialize db and connect to port in workbench. I tried having MySQL container with the node container in the same docker network, and I was getting the same errors. I tried with different versions, node:18, 20 and 22 alpine, and MySQL 8.0, 9.0.1 and 8.0.33.
I also tried to docker inspect
the MYSQL container, finding gateway ip, using that ip as a host, all it would do is change the errors to that ip.
Just wanna point out I am using Sequelize in my app.
Alternative Docker compose file:
services:
server:
build:
context: .
ports:
- "3001:3001"
depends_on:
mysql:
condition: service_healthy
mysql:
image: mysql:8.0.0
container_name: mysql2
environment:
MYSQL_USER: admin
MYSQL_ROOT_PASSWORD: password
MYSQL_PASSWORD: password
ports:
- "3307:3306"
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-p'password'"]
interval: 30s
timeout: 10s
retries: 5
start_period: 30s