Home >Database >Mysql Tutorial >Why am I getting ECONNREFUSED when connecting to MySQL container from my Node.js application?
Node.js ECONNREFUSED While Connecting to MySQL Docker Container
In a Docker compose setup involving a MySQL container and a Node.js web service, connecting to MySQL from Node.js resulted in the ECONNREFUSED error, despite having an established Docker link and properly configured database settings.
Problem Statement
The problem stemmed from a misunderstanding of Docker port mapping. In the Docker compose file:
ports: - "3307:3306"
This maps the host port 3307 to the container port 3306. While this allows external access to the MySQL container's database from the host, it does not change the internal port the container listens on.
Solution
To resolve the issue, the Node.js configuration and Docker command were adjusted:
Node.js Configuration
const config = { host: 'mysql', // Use the Docker service name instead of 'localhost' database: 'mydb', port: '3306', // Connect to the container's native port user: 'mysql', password: '1234', connectionLimit: 10 }
Docker Command
command: ["./wait-for-it.sh", "mysql:3306"] // Wait for the MySQL container to start on port 3306
Explanation
By using the Docker service name (mysql) as the host in the Node.js configuration, we ensure that the connection attempt is made to the container, not the host. Additionally, by changing the wait-for-it script argument to 3306, we wait for MySQL to be ready on its native port within the container.
Once these changes were implemented, the ECONNREFUSED error was resolved, and the Node.js application could successfully connect to the MySQL Docker container.
The above is the detailed content of Why am I getting ECONNREFUSED when connecting to MySQL container from my Node.js application?. For more information, please follow other related articles on the PHP Chinese website!