Home  >  Article  >  Database  >  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
Barbara StreisandOriginal
2024-11-10 19:46:02166browse

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
};

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"]

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!

Statement:
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