Encountering a Connection Refused Error (ECONNREFUSED) with Docker Compose and MySQL when using NodeJS

Setting up containers for my NestJS + TypeORM + MySQL environment using Docker Compose on a Windows 10 host is proving to be challenging as I keep encountering an ECONNREFUSED error:

connect ECONNREFUSED 127.0.0.1:3306 +2ms
backend_1  | Error: connect ECONNREFUSED 127.0.0.1:3306
backend_1  |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1145:16)
backend_1  |     --------------------
...

A Dockerfile has been created to configure the NestJS API container:

FROM node:12-alpine
WORKDIR /usr/src/app

COPY package.json .
RUN npm install

EXPOSE 3000

CMD /wait-for-it.sh db:3306 -- npm start

COPY . .

This is referenced in the docker-compose.yml:

version: "3.8"
networks:
  app-tier:
    driver: bridge
services:
  db:
    image: mysql
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    expose:
      - "3306"
    ports:
      - "3306:3306"    
    networks:
      - app-tier      
    environment:
      MYSQL_DATABASE: school
      ...
  backend:
    depends_on:
      - db
    build: .
    ports:
      - "3000:3000"
    networks:
      - app-tier      

TypeORM configuration matching the Docker Compose file:

export const DB_CONFIG: TypeOrmModuleOptions = {
    type: 'mysql',
    host: 'db',
    port: 3306,
    username: 'dbuser',
    password: 'dbuser',
    database: 'school',
    entities: [],
    synchronize: true,
};

Despite trying various solutions like changing output ports and adding explicit network settings, the issue persists. Any suggestions?

Edit 1

Added MYSQL_ROOT_HOST and wait-for-it.sh as recommended, but still no luck.

Answer №1

It seems like your database is taking longer to start up, causing your application to launch before the database is ready. To address this issue, modify your docker-compose.yml file with the following configuration:

version: "3.8"

networks:
  app-tier:
    driver: bridge

services:
  db:
    image: mysql
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    expose:
      - "3306"
    ports:
      - "3306:3306"    
    networks:
      - app-tier      
    environment:
      MYSQL_DATABASE: school
      MYSQL_ALLOW_EMPTY_PASSWORD: ok
      MYSQL_ROOT_PASSWORD: root
      MYSQL_USER: dbuser
      MYSQL_PASSWORD: dbuser
      MYSQL_ROOT_HOST: '%'
  backend:
    depends_on:
      - db
    build: .
    command: bash -c 'while !</dev/tcp/db/3306; do sleep 1; done; npm start'
    ports:
      - "3000:3000"
    networks:
      - app-tier   

Answer №2

One helpful strategy is to implement health checks to ensure a service is functioning properly and gracefully handle any failures if it does not meet the required criteria within a set number of attempts.

An example of a health check for a database service could be:

healthcheck:
  test: mysqladmin ping -h mysql --user=$$MYSQL_USER --password=$$MYSQL_ROOT_PASSWORD
  interval: 30s
  timeout: 12s
  retries: 10

Additionally, in the backend section, include a dependency like this:

depends_on:
  db:
    condition: service_healthy

This approach ensures that your backend service will only start once the database is confirmed as healthy, with 10 connection attempts made at 30-second intervals before failing. By setting such parameters, you avoid potential hang-ups if the MySQL server fails to come online indefinitely.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with locking on a compact table when running basic queries are causing frustrations

One of our database tables is called DashboardItem, with the following list of columns: CREATE TABLE `DashboardItem` ( `id` int(11) NOT NULL AUTO_INCREMENT, `client_dashboard_id` int(11) NOT NULL, `type` varchar(100) COLLATE utf8mb4_unicode_ci DEFAUL ...

I encountered an issue with my promise where the data was undefined, causing me to have trouble properly setting the error. Could this be

Recently, I encountered an issue while trying to sign up my users using a simple form. An error popped up indicating that the data (promise argument) is undefined: Unhandled Runtime Error TypeError: Cannot read property 'message' of undefined (a ...

Node.js: Can we include global-like variables in a required module similar to __dirname and __filename?

One interesting approach is to override the wrap method of a module and introduce a global variable called 'myVar': var Module = require("module"); (function() { Module.wrap = function(script) { var wrapper = [ '(function (expor ...

How can generators and Q be used in the simplest fs.readFile example?

I have relied on node's async as my primary flow control mechanism for quite some time now. It has always worked well for me, without the need to delve into discussions or further reading about it. Now, I am intrigued by the possibility of using gene ...

What is the best way to combine arrays?

Here is the array retrieved from the database: [ { "_id": "58144e6c0c8d7534f4307269", "doctor_id": "5813221ace684e2b3f5f0a6d", "prescription": [ { "_id": "58144e6c0c8d7534f430726a", "medicine_id": "1001124 ...

Using TypeORM with a timestamp type column set to default null can lead to an endless loop of migrations being

In my NestJs project using TypeORM, I have the following column definition in an entity: @CreateDateColumn({ nullable: true, type: 'timestamp', default: () => 'NULL', }) public succeededAt?: Date; A migration is gene ...

What is the best approach for managing authentication across different frameworks?

My Ruby web applications utilize OpenID for authentication and save session information in a cookie. To address some limitations with API and AJAX functionality within my Ruby frameworks, I have integrated node.js services into the mix. The concern arises ...

Using the digitallyseamless/nodejs-bower-grunt docker image to containerize npm and bower installations

I've been exploring the possibilities of using Docker to execute npm and bower install commands. Below is my setup: ./package.json { "name": "bignibou-client", "version": "0.1.0", "engines": { "node": "0.10.x" }, "devDependencies": { ...

Leveraging Javascript Modules within a Typescript Vue Application

The issue at hand I've encountered a problem while attempting to integrate https://github.com/moonwave99/fretboard.js into my Vue project. My initial approach involved importing the module into a component as shown below: <template> <div&g ...

Having some trouble getting @angular/cli to install properly on my Ubuntu system

After numerous attempts to install @angular/cli on Ubuntu terminal, I kept encountering the following error: **npm ERR! 404 Not Found: @angular/cli@latest**. Even though I had installed nodejs with nvm and set NVM_BIN path to /root/.nvm/versions/node/v9. ...

Utilizing Node.js createReadStream for Asynchronous File Reading

For a specific project, I developed a module that is responsible for splitting files based on the '\r\n' delimiter and then sending each line to an event listener in app.js. Below is a snippet of the code from this module. var fs = req ...

What is the best way to effectively adjust the code structure in a Node.JS project?

[Summarized] Focus on the bold parts. Although I am relatively new to Node.JS, I have been able to successfully build some projects. However, I have come across a burning question that has left me frustrated after searching Google for answers without much ...

JShint malfunctioning

My attempt to install jshint using npm with the command npm install -g jshint didn't seem to work correctly. Even after I reinstalled node due to previous issues, running the command again yielded no results in the terminal. The output from my install ...

Storing and updating object property values dynamically within a for...in loop in JavaScript

I am currently working on a Node application powered by express and I am looking to properly handle apostrophes within the incoming request body properties. However, I am not entirely convinced that my current approach is the most efficient solution. expo ...

The SMTP request for a one.com domain email is experiencing issues when sent from the render.com server

I have set up an Express JS server on render.com to handle SMTP calls to an email service hosted on one.com with a custom domain. Utilizing nodemailer to manage the SMTP call: app.post("/send-mail", validate(schema), (req, res) => { console. ...

Unlocking Spotify: A Guide to Generating an Access Token through Web API Node

I visited the following link for more information: https://www.npmjs.com/package/spotify-web-api-node Here is a code snippet: var SpotifyWebApi = require('spotify-web-api-node'); // credentials are optional var spotifyApi = new SpotifyWebApi( ...

Having trouble with firebase admin code completions not functioning properly in vscode?

I've attempted to install the Typescript integration for Firebase using: npm install --save-dev @types/firebase Unfortunately, I have not had any success. The "firebase-admin" and "firebase-functions" packages do not provide code completion or intel ...

Attempting to create a redirection landing page

I have a process where I create a new user and save it in my database with the following code snippet: const newUser = new User({ username: userId, password: pass, nameOfUser: user_name, emailOfUser: user_email ); newUser.save(); res.redir ...

BlurDataURL for Data URLs in Next.js

NextJS 11 brings the exciting feature of using the Image component with a blur placeholder. To utilize this with dynamic images, we need to make use of the blurDataURL, which is a Data URL. I am interested in taking my original image and resizing it to a ...

Why does the MEAN Stack continue to route using the '#' symbol in the URL?

Currently navigating the realm of back end development. Started off by following a guide on express from thinkster. In need of some clarification. Initially, I grasped that front-end and back-end routing serve different purposes. Front-end routing relates ...