Connecting to MySQL Docker Container: Resolving ECONNREFUSED
This article addresses the frequently encountered ECONNREFUSED error when attempting to connect to a MySQL Docker container from Node.js.
Background
In a multi-container Dockerized application, it's common to have a database container (e.g., MySQL) and connect to it from other containers (e.g., Node.js web application). However, this connection can fail with an ECONNREFUSED error, signaling that the Node.js application cannot reach the database.
Understanding the Issue
When configuring Docker containers, port mapping is crucial. A common misconception is that port mapping, such as "3307:3306," means the container is listening on port 3307. However, containers typically listen on their internal ports. In the case of MySQL, it listens on port 3306 within the container.
Solution: Modify Node.js Configuration and DNS
To resolve this issue, modify the Node.js configuration to connect to the database on port 3306 and specify the correct DNS. In this case, the DNS is 'mysql', as defined in the docker-compose.yml.
This updates the Node.js configuration as follows:
const config = { host: 'mysql', // Replace 'localhost' with the container DNS database: 'mydb', port: '3306', user: 'mysql', password: '1234', connectionLimit: 10 }
Additionally, modify the command in the docker-compose.yml:
command: ["./wait-for-it.sh", "mysql:3306"] // Update the port number
This ensures that the "wait-for-it.sh" script waits for MySQL to listen on port 3306 within the container.
Conclusion
By understanding the port mapping mechanism and updating the Node.js configuration and DNS, it's possible to resolve the ECONNREFUSED error and establish a successful connection between the Node.js application and the MySQL container within a Dockerized environment.
The above is the detailed content of Why Am I Getting ECONNREFUSED When Connecting to a MySQL Docker Container from Node.js?. For more information, please follow other related articles on the PHP Chinese website!