-1

I am trying to build an application using docker and MySQL but I am not able to connect to the MySQL container through Node.js. I don't know if using knex is causing this but the error is ECONNREFUSED.

{
    "errno": -111,
    "code": "ECONNREFUSED",
    "syscall": "connect",
    "address": "127.0.0.1",
    "port": 3306,
    "fatal": true
}

Docker.compose.yaml

version: "3.8"
services: 
  app:
    build: 
      context: .
      dockerfile: Dockerfile
    ports: 
      - 3000:3000
    volumes: 
      - .:/app
      - /app/node_modules
  
  mysql_server:
    image: mysql:8.0
    ports:
      - 3307:3306
    environment: 
      - MYSQL_DATABASE=transaction_app
      - MYSQL_ROOT_PASSWORD=root

Knex connection

const db= knex ({
  client: 'mysql2',
  connection: {
    host: '127.0.0.1',
    port: 3306,
    user: 'root',
    password: '',
    database: 'transaction_app'
  }
});
NevinTroy
  • 13
  • 5

1 Answers1

1

You need to use mysql_server as the host name when you connect. In a container, localhost and 127.0.0.1 means the container itself.

Like this

const db= knex ({
  client: 'mysql2',
  connection: {
    host: 'mysql_server',
    port: 3306,
    user: 'root',
    password: '',
    database: 'transaction_app'
  }
});

More info here.

Hans Kilian
  • 18,948
  • 1
  • 26
  • 35