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 }
Modified Docker Compose File:
command: ["/bin/bash", "./wait-for-it.sh", "mysql:3306"] // Match the port MySQL is listening on
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!