Home > database >  Running local NodeJS application can't connect to MySQL docker container running locally
Running local NodeJS application can't connect to MySQL docker container running locally

Time:12-06

I have an SQL docker container running on my host using docker-compose.

mysql -h 127.0.0.1 -P 3306 -u root -p

This works perfectly. But...

When I am in my host trying to connect to it using my NodeJS app it fails -

            client: 'mysql2',
            connection: dbSsl ? async () => {
                const token  = await rds.getAuthPluginPromise();
                return {
                    host : 127.0.0.1,
                    port : 3306,
                    user : root,
                    ssl: "",
                    database : "myapp",
                    multipleStatements: true,
                    authPlugins: {
                        mysql_clear_password: () => () => {
                            return Buffer.from(token   '\0')
                        }
                    }
                };
            } : databaseUrl,
            pool: {min: dbPoolMin, max: dbPoolMax, propagateCreateError: false},
            searchPath: "myapp",
            requestTimeout: 30000,
        });```

docker compose

      mysql:
    image: arm64v8/mysql:oracle
    container_name: mysql
    restart: always
    ports:
      - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: "password"


CONTAINER ID   IMAGE                  COMMAND                  CREATED         STATUS         PORTS                               NAMES
6369b421dc7d   arm64v8/mysql:oracle   "docker-entrypoint.s…"   3 minutes ago   Up 3 minutes   0.0.0.0:3306->3306/tcp, 33060/tcp   mysql```

CodePudding user response:

Perhaps, you miss some environment variables in your container. Try adding the following:

mysql:
  image: arm64v8/mysql:oracle
  container_name: mysql
  restart: always
  ports:
    - "3306:3306"
  environment:
    MYSQL_ROOT_PASSWORD: "password"
    MYSQL_DATABASE: "myapp"               ### <-- you need this one at least

Also, try adding more debug in your code. Just right after your server starts, try something like:

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "password",
  database : "myapp"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
});

If this works, then debug the code you published in your question.

  • Related