TypeORM with MySQL ECONNREFUSED 10.104.38.229:3306 when running on kubernetes pod

2/19/2021

I am trying to create a simple NodeJs app to connect with a MySQL database. The app and MySQL DB both are hosted inside of a Kubernetes cluster. I am using the K8s service to connect the app to the MySQL pod.

When I use the MySQL adapter for the connection it works fine. However, when I connect it via Typeorm library, it throws an ECONNREFUSED on the first attempt. However, When I restart the app the connection get establishes.

can anyone tell me why I'm seeing this strange behavior and how can I solve this problem.

my error is like this:

[server] Error: connect ECONNREFUSED 10.104.38.229:3306
[server]     at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1138:16) {
[server]   errno: -111,
[server]   code: 'ECONNREFUSED',
[server]   syscall: 'connect',
[server]   address: '10.104.38.229',
[server]   port: 3306,
[server]   fatal: true
[server] }

my index.ts is like this:

import { app } from './app';
import {
  createConnection,
  createConnections,
  getConnectionManager,
} from 'typeorm';
import mysql from 'mysql';
const port = 3000;

const start = async () => {
  try {
    const connectionManager = getConnectionManager();
    const connections = connectionManager.create({
      type: 'mysql',
      host: 'xcute-mysql-srv',
      port: 3306,
      username: 'root',
      password: 'root',
      database: 'test',
    });
    await connections.connect();
    console.log('Succesfully Connected');

    // const connection = mysql.createConnection({
    //   host: 'xcute-mysql-srv',
    //   port: 3306,
    //   user: 'root',
    //   password: 'root',
    //   database: 'test',
    // });
    // connection.connect(() => {
    //   console.log('Succesfully Connected');
    // });
  } catch (error) {
    console.log(error);
  }
  app.listen(port, () => console.log(`Listening at port ${port} !!`));
};

start();

Edit1:

   await createConnection({
      type: 'mysql',
      host: 'xcute-mysql-srv',
      port: 3306,
      username: 'root',
      password: 'root',
      database: 'test',
    });
    console.log('Succesfully Connected');

Also throwing the same error

-- dev_rrp
kubernetes
mysql
node.js
typeorm

1 Answer

2/19/2021

Have you tried creating the connection using the createConnection function instead of calling the ConnectionManager create method? This is how I do it in my own application and it works fine:

const start = async () => {
  try {
    await createConnection({
      type: 'mysql',
      host: 'xcute-mysql-srv',
      port: 3306,
      username: 'root',
      password: 'root',
      database: 'test',
    });
    console.log('Succesfully Connected');

  } catch (error) {
    console.log(error);
  }
  app.listen(port, () => console.log(`Listening at port ${port} !!`));
};

start();
-- Nathan
Source: StackOverflow