Home > Database > Mysql Tutorial > How to Fix 'ECONNREFUSED' Errors When Connecting to MySQL Docker Container in Node.js?

How to Fix 'ECONNREFUSED' Errors When Connecting to MySQL Docker Container in Node.js?

Barbara Streisand
Release: 2024-11-10 19:46:02
Original
259 people have browsed it

How to Fix

Resolving Node.js MySQL Docker Connection ECONNREFUSED

In Node.js, the error "ECONNREFUSED" typically indicates a connection failure when attempting to connect to a database. When connecting to a MySQL database running within a Docker container, this issue can be resolved by ensuring proper port mapping.

By default, Docker maps the host port to a different port within the container. In your provided Docker Compose file, the MySQL container is exposed on port 3307 on the host, while internally listening on port 3306.

To resolve this discrepancy, modify the Node.js configuration to specify the correct port for connecting to MySQL:

const config = {
  host: 'mysql', // Use the container name
  database: 'mydb',
  port: '3306', // Use the internal container port
  user: 'mysql',
  password: '1234',
  connectionLimit: 10
};
Copy after login

Additionally, ensure that the Docker Compose command uses the correct port when waiting for MySQL to become available:

command: ["./wait-for-it.sh", "mysql:3306"]
Copy after login

These modifications will allow Node.js to connect to the MySQL container successfully.

The above is the detailed content of How to Fix 'ECONNREFUSED' Errors When Connecting to MySQL Docker Container in Node.js?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template