Home > Net >  Connecting to Mysql (Docker) with NodeJS
Connecting to Mysql (Docker) with NodeJS

Time:04-21

This is my situation.

With NodeJS, I want to connect to mysql which is mounted on docker.

However, I can't do it. I have this error which is quite explicit but impossible to solve for me.

[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Application Name: RESTFull API - Development
Environment: development
Server is listening on port 3000
getaddrinfo ENOTFOUND db # <------------ Error here
[nodemon] app crashed - waiting for file changes before starting...

Does anyone have any idea how I can solve this? Note: Only Mysql is on Docker.

## docker-compose.yml
version: '3.8'

services:
  db:
    image: mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: 'nodejs-restfull-api-development'
    expose:
      - 3306
    volumes:
      - db-config:/etc/mysql
      - db-data:/var/lib/mysql

  adminer:
    image: adminer:latest
    depends_on:
      - db
    environment:
      ADMINER_DEFAULT_DB_DRIVER: mysql
      ADMINER_DEFAULT_DB_HOST: db
      ADMINER_DESIGN: nette
      ADMINER_PLUGINS: tables-filter tinymce
    ports:
      - "8080:8080"

volumes:
  db-config:
  db-data:
const database = mysql.createConnection({
  host: 'db',
  user: config.get('db.user'),
  password: config.get('db.password'),
  database: config.get('db.database'),
  port: config.get('db.port'),
  connectTimeout: config.get('db.connectTimeout')
});

database.connect(err => {
  if (err) {
    console.log(err.message);
    process.exit(1);
  } else {
    console.log('Connected to database');
  }
});

CodePudding user response:

You don't tell us, but I assume your Node app is running on the host and not in a container? If that's the case, then you need to expose the MySQL port to the host, so it's reachable. You also need to use localhost as the hostname in your configuration.

Expose the port by changing the database part of your docker-compose file to

  db:
    image: mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: 'nodejs-restfull-api-development'
    ports:
      - 3306:3306
    volumes:
      - db-config:/etc/mysql
      - db-data:/var/lib/mysql

And change your Node configuration to

const database = mysql.createConnection({
  host: 'localhost',
  user: config.get('db.user'),
  password: config.get('db.password'),
  database: config.get('db.database'),
  port: config.get('db.port'),
  connectTimeout: config.get('db.connectTimeout')
});
  • Related