尝试从微服务内部连接数据库,但无法连接数据库
错误:连接ECONNREFUSED 172.18.0.2:3306
service / index.js
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
console.log("Listening at 8080");
var mysql = require('mysql');
var con = mysql.createConnection({
host: "database",
user: "root",
password: "password"
});
con.connect(function(err) {
if (err) throw err;
console.log("Database Connected!");
});
docker-compose.yml
version: '3'
services:
database:
build:
./database
ports:
- "6603:3306"
image: "test-mysql"
container_name: "test-mysql"
service:
build:
./service
ports:
- "8080:8080"
depends_on:
- database
image: "test-nodejs"
container_name: "test-nodejs"
restart: on-failure
我尝试使用不同的设置连接到数据库。
1)没有端口
var con = mysql.createConnection({
host: "database",
user: "root",
password: "password"
});
2)指定的端口3306
var con = mysql.createConnection({
host: "database",
user: "root",
password: "password"
port: 3306
});
3)指定端口6603
var con = mysql.createConnection({
host: "database",
user: "root",
password: "password",
port: 6603
});
数据库/ Dockerfile
FROM mysql
ENV MYSQL_DATABASE=test
ENV MYSQL_ROOT_PASSWORD=password
EXPOSE 6603:3306
COPY ./schema.sql /docker-entrypoint-initdb.d/
我的node.js微服务基本上可以如何发现数据库服务?
修改
我怀疑在nodejs启动时数据库还没有准备好,所以我在连接数据库和更改错误之前增加了一些延迟
更新代码
setTimeout(function(){
var mysql = require('mysql');
var con = mysql.createConnection({
host: "database",
user: "root",
password: "password"
});
con.connect(function(err) {
if (err) throw err;
console.log("Database Connected!");
});
}, 20 * 1000);
输出
Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
答案 0 :(得分:0)
您错过订单:
首先连接到数据库,然后监听端口。
var http = require('http');
var mysql = require('mysql');
var con = mysql.createConnection({
host: "database",
user: "root",
password: "password"
} );
con.connect(function(err) {
if (err) throw err;
console.log("Database Connected!");
});
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
console.log("Listening at 8080");
答案 1 :(得分:0)
可能您使用的MySQL版本不支持您尝试的登录名。尝试使用mysql v5.7:
docker run -d -p 6603:3306 --name mysql-container -e MYSQL_ROOT_PASSWORD=password mysql:5.7
答案 2 :(得分:0)
数据库端口没有被转换,因为它在容器内。只需在您的应用中使用 3306