Home > Database > Mysql Tutorial > Why Does My Node.js App Get an ECONNREFUSED Error When Connecting to a MySQL Docker Container?

Why Does My Node.js App Get an ECONNREFUSED Error When Connecting to a MySQL Docker Container?

Linda Hamilton
Release: 2024-11-11 00:01:03
Original
602 people have browsed it

Why Does My Node.js App Get an ECONNREFUSED Error When Connecting to a MySQL Docker Container?

Node.js Connection to MySQL Docker Container ECONNREFUSED

Issue:

Despite having a Docker compose file with linked MySQL and Node.js containers, the Node.js app encounters an ECONNREFUSED error while attempting to connect to the MySQL container using port 3307.

Analysis:

The Docker compose file maps the 3307 port of the host to 3306 in the container. However, the MySQL container is listening on 3306 internally. This leads to the issue where Node.js attempts to connect to port 3307 of the host, which is not the port the container is listening on.

Solution:

To resolve the issue, adjust the MySQL configuration and Docker compose file as follows:

Modified MySQL Configuration:

const config = {
    host: 'mysql',  // Use the MySQL container DNS name
    database: 'mydb',
    port: '3306',  // Match the port the MySQL container is listening on
    user: 'mysql',
    password: '1234',
    connectionLimit: 10
}
Copy after login

Modified Docker Compose File:

command: ["/bin/bash", "./wait-for-it.sh", "mysql:3306"]  // Match the port MySQL is listening on
Copy after login

By making these modifications, the Node.js app will now connect to the MySQL container using the correct port, and the ECONNREFUSED error should be resolved.

The above is the detailed content of Why Does My Node.js App Get an ECONNREFUSED Error When Connecting to a MySQL Docker Container?. 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