I am trying to connect From Node.js on Localhost to MySQL instance running on docker using docker-compose.
Node.js gives me this error: ENOTFOUND db
, Full error message bellow.
[nodemon] restarting due to changes... [nodemon] starting `node app.js` Application Name: RESTFull API - Development Environment: development Server is listening on port 3000 getaddrinfo ENOTFOUND db # <------------ Error here [nodemon] app crashed - waiting for file changes before starting...
Here is docker-compose.yml that contains MySQL and adminer services.
## docker-compose.yml version: '3.8' services: db: image: mysql restart: always environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: 'nodejs-restfull-api-development' expose: - 3306 volumes: - db-config:/etc/mysql - db-data:/var/lib/mysql adminer: image: adminer:latest depends_on: - db environment: ADMINER_DEFAULT_DB_DRIVER: mysql ADMINER_DEFAULT_DB_HOST: db ADMINER_DESIGN: nette ADMINER_PLUGINS: tables-filter tinymce ports: - "8080:8080" volumes: db-config: db-data:
Here is my node.js database connection config.
const database = mysql.createConnection({ host: 'db', user: config.get('db.user'), password: config.get('db.password'), database: config.get('db.database'), port: config.get('db.port'), connectTimeout: config.get('db.connectTimeout') }); database.connect(err => { if (err) { console.log(err.message); process.exit(1); } else { console.log('Connected to database'); } });
Advertisement
Answer
You don’t tell us, but I assume your Node app is running on the host and not in a container? If that’s the case, then you need to expose the MySQL port to the host, so it’s reachable. You also need to use localhost
as the hostname in your configuration.
Expose the port by changing the database part of your docker-compose file to
db: image: mysql restart: always environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: 'nodejs-restfull-api-development' ports: - 3306:3306 volumes: - db-config:/etc/mysql - db-data:/var/lib/mysql
And change your Node configuration to
const database = mysql.createConnection({ host: 'localhost', user: config.get('db.user'), password: config.get('db.password'), database: config.get('db.database'), port: config.get('db.port'), connectTimeout: config.get('db.connectTimeout') });