Node.js connect to MySQL Docker container ECONNREFUSED
When attempting to connect to a MySQL Docker container using Node.js, an ECONNREFUSED error (e.g., ECONNREFUSED 127.0.0.1:3307) may occur. This error indicates that Node.js is unable to establish a connection to the MySQL container.
Docker Compose Configuration
As exemplified in the provided docker-compose.yml file, it is essential to understand that the port mapping configuration (e.g., 3307:3306) only specifies how Docker maps host ports to container ports. The container itself still listens on its default port (e.g., 3306 for MySQL).
Node.js Connection Configuration
To resolve the ECONNREFUSED error, ensure that the Node.js application is configured to connect to the MySQL container's internal port. In the example provided, the host property should be set to 'mysql' and the port property should be set to '3306'.
const config = { host: 'mysql', database: 'mydb', port: '3306', user: 'mysql', password: '1234', connectionLimit: 10 };
Command in Docker Compose
Additionally, the command property in the docker-compose.yml file should be updated to wait for MySQL on port 3306 instead of 3307.
command: ["./wait-for-it.sh", "mysql:3306"]
Note: It's recommended to use the wait-for-it.sh script to ensure that the MySQL container is fully initialized before attempting to connect from Node.js. This script can be obtained from https://github.com/vishnubob/wait-for-it.
By following these steps, it should be possible to establish a connection between the Node.js application and the MySQL Docker container.
The above is the detailed content of Why am I getting an ECONNREFUSED error when connecting to my MySQL Docker container from Node.js?. For more information, please follow other related articles on the PHP Chinese website!