Node.js connect to MySQL Docker container ECONNREFUSED

This:

mysql:
    image: mysql:5.7
    environment:
    ...
    ports:
      - "3307:3306"

Means that Docker will map the 3307 port of the host to the 3306 port of the container. So you can access from Sequel to localhost:3307.

However, it does not mean that the container is listenting to 3307; the container is in fact still listening to 3306. When others containers tries to access the mysql DNS, it gets translated to the internal container IP, therefore you must connect to 3306.

So your node config should look like:

const config = {
    host: 'mysql',
    database: 'mydb',
    port: '3306',
    user: 'mysql',
    password: '1234',
    connectionLimit: 10
}

And this in your docker-compose.yml:

command: ["./wait-for-it.sh", "mysql:3306"]

Note: wait-for-it.sh script comes from: https://github.com/vishnubob/wait-for-it

Leave a Comment