Can't connect node js with mysql in docker container

592 Views Asked by At

error message I am facing after running docker composee

Express server is runnig at port no : 8000
backend-web-1  | DB connection failed
backend-web-1  |  Error : {
backend-web-1  |   "errno": -111,
backend-web-1  |   "code": "ECONNREFUSED",
backend-web-1  |   "syscall": "connect",
backend-web-1  |   "address": "127.0.0.1",
backend-web-1  |   "port": 3306,
backend-web-1  |   "fatal": true
backend-web-1  | }

folder structure of my app

Docker file for mysql

FROM mysql
WORKDIR /app
COPY ./mysql.sql /docker-entrypoint-initdb.d/

Docker file of node js

FROM node:18-alpine
WORKDIR /app
COPY *package.json /app
RUN npm install
EXPOSE 8000
COPY . /app
CMD ["node" ,"index.js"]

Docker compose file


services: 
  db: 
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    build: ./dbinit
    environment: 
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: timesheet
      restart: always
    ports:
      - "3305:3309"
  web:
    depends_on:
      - "db"
    build: ./app
    environment:
      MYSQL_HOST: db
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: timesheet
    ports:
      - "5000:8000"
 

      

I've been trying this for three days. Both Node JS and MySQL images can be built, an issue occurs when Node.js tries to connect to the MySQL database.

here is the code of backend server index.js

  // Create Connection

var mysqlConnection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'timesheet',
    multipleStatements: true
});


  // Connecting database
  mysqlConnection.connect((err) => {
    if (!err)
        console.log('DB connection succeded.');
    else
        console.log('DB connection failed \n Error : ' + JSON.stringify(err, undefined, 2));
});


app.listen(8000, () => console.log('Express server is runnig at port no : 8000'));
1

There are 1 best solutions below

0
Mafor On

Although I can see an attempt to set a correct DB host for the web service in the docker-compose file, the backend application seems to be trying to connect to localhost:3306, which is wrong. From the back-end code snippet you posted, it's hard to understand, how the host should be picked from the MYSQL_HOST environment variable.