Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.3K
Views
TCPConnectWrap.afterConnect - node can't get data from mysql when are in docker compose

I'm trying to connect node with mysql through dokcer-compose. I can access mysql with workbench but when I try to connect with node I get the error:

Error: connect ECONNREFUSED 127.0.0.1:3306
     at TCPConnectWrap.afterConnect [as oncomplete] (net.js: 1054: 14))

Does anyone know what is going on?

docker-compose.yml

version: '3'

services:

  #App Service
  app:
    image: "node:alpine"
    container_name: cms-node
    restart: unless-stopped
    tty: true
    working_dir: /app
    environment:
      - NODE_ENV=production
    ports:
      - 1234:1234
    volumes:
      - ./:/app
    links:
      - db
    depends_on:
      - db

  #Mysql Service
  db:
    image: mysql:latest
    container_name: cms-mysql
    restart: unless-stopped
    # command: --default-authentication-plugin=mysql_native_password
    environment:
      MYSQL_DATABASE: CMS
      MYSQL_USER: root
      MYSQL_PASSWORD: root
      MYSQL_ROOT_PASSWORD: root
    ports:
      - 3306:3306

node create connection

const db: Connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'CMS',
});

export default db;

node try to connect

db.connect((err) => {
            if (err) {
                throw err;
            }
            console.log('Connected!');
        });
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You should use the link name (by default, the name of the linked service) as the hostname to connect to. See the docker-compose.yml documentation for details.

So just use host: 'db' instead of host: 'localhost'

over 4 years ago · Santiago Trujillo Report

0

Yes, we have to use service name from docker-compose.yml. I faced a similar issue when there was a custom front end API Gateway server (working as proxy) written in node.js connecting to other two services. So replacing localhost:3001 with serviceName:30001 fixed the issue.

Example code:

...
const proxy = require('express-http-proxy');
...

app.use('/json-parser', proxy('json_parsing_api:3001'));
app.get('/json-parser/json-to-person', proxy('json-to-person'));
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!