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.
JavaScript
x
8
1
[nodemon] restarting due to changes
2
[nodemon] starting `node app.js`
3
Application Name: RESTFull API - Development
4
Environment: development
5
Server is listening on port 3000
6
getaddrinfo ENOTFOUND db # <------------ Error here
7
[nodemon] app crashed - waiting for file changes before starting
8
Here is docker-compose.yml that contains MySQL and adminer services.
JavaScript
1
32
32
1
## docker-compose.yml
2
version: '3.8'
3
4
services:
5
db:
6
image: mysql
7
restart: always
8
environment:
9
MYSQL_ROOT_PASSWORD: root
10
MYSQL_DATABASE: 'nodejs-restfull-api-development'
11
expose:
12
- 3306
13
volumes:
14
- db-config:/etc/mysql
15
- db-data:/var/lib/mysql
16
17
adminer:
18
image: adminer:latest
19
depends_on:
20
- db
21
environment:
22
ADMINER_DEFAULT_DB_DRIVER: mysql
23
ADMINER_DEFAULT_DB_HOST: db
24
ADMINER_DESIGN: nette
25
ADMINER_PLUGINS: tables-filter tinymce
26
ports:
27
- "8080:8080"
28
29
volumes:
30
db-config:
31
db-data:
32
Here is my node.js database connection config.
JavaScript
1
18
18
1
const database = mysql.createConnection({
2
host: 'db',
3
user: config.get('db.user'),
4
password: config.get('db.password'),
5
database: config.get('db.database'),
6
port: config.get('db.port'),
7
connectTimeout: config.get('db.connectTimeout')
8
});
9
10
database.connect(err => {
11
if (err) {
12
console.log(err.message);
13
process.exit(1);
14
} else {
15
console.log('Connected to database');
16
}
17
});
18
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
JavaScript
1
12
12
1
db:
2
image: mysql
3
restart: always
4
environment:
5
MYSQL_ROOT_PASSWORD: root
6
MYSQL_DATABASE: 'nodejs-restfull-api-development'
7
ports:
8
- 3306:3306
9
volumes:
10
- db-config:/etc/mysql
11
- db-data:/var/lib/mysql
12
And change your Node configuration to
JavaScript
1
9
1
const database = mysql.createConnection({
2
host: 'localhost',
3
user: config.get('db.user'),
4
password: config.get('db.password'),
5
database: config.get('db.database'),
6
port: config.get('db.port'),
7
connectTimeout: config.get('db.connectTimeout')
8
});
9