skip to Main Content

I am starting two docker containers through docker-compose.

The contents of docker-compose.yml file:

version: "3.7"

services:
  app:
    image:  my-app:latest
    ports:  
      - 8000:8000
    working_dir: /usr/app/MyApp
    environment: 
      MYSQL_ROOT_PASSWORD: myawesomepassword
      MYSQL_DATABASE: myawesomedb
      MYSQL_USER: root
      MYSQL_PASSWORD: myawesomepassword
  mysql:
    image:  mysql:5.6
    volumes:
      - db-data:/var/lib/mysql 
    environment: 
      MYSQL_ROOT_PASSWORD: myawesomepassword
      MYSQL_DATABASE: myawesomedb
volumes:
  db-data: {}

The app is connecting to the database like this:

import mysql from 'mysql2/promise.js';

var config = {
    app: {
        host: 'http://localhost',
        port: '8000'
    },
    database: {
        host: 'host.docker.internal',
        port: 3306,
        database: process.env['MYSQL_DATABASE'],
        user: process.env['MYSQL_USER'],
        password: process.env['MYSQL_PASSWORD']
    }
}

const {host, port, user, password, database } = config.database;

// Error occurs here
const connection = await mysql.createConnection({ host, port, user, password });

When the app service attempts to connect to mysql, I receive this error:

Error: Access denied for user 'root'@'localhost' (using password: YES)

Any advice is welcomed. Thank you in advanced

2

Answers


  1. Chosen as BEST ANSWER

    Changing the database config from:

        database: {
            host: 'host.docker.internal',
            port: 3306,
            database: process.env['MYSQL_DATABASE'],
            user: process.env['MYSQL_USER'],
            password: process.env['MYSQL_PASSWORD']
        }
    

    to:

        database: {
            host: 'mysql',
            port: 3306,
            database: process.env['MYSQL_DATABASE'],
            user: process.env['MYSQL_USER'],
            password: process.env['MYSQL_PASSWORD']
        }
    

    Resolved the connection issue.

    Thank you @FirstOne for your time and attention.


  2. By the error, it generally means you’re pointing the app service to localhost, which would mean the app container itself. In your case, you’d be pointing to the host machine.
    You need to update the address of the database in your config to point to the other container.

    Since you’re using mysql as the database service name, just update your code to be:

    database: {
        host: 'mysql',
        port: 3306,
        ...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search