gpt4 book ai didi

mysql - 带有错误 : connect ECONNREFUSED 的 docker mysql

转载 作者:行者123 更新时间:2023-11-29 03:16:01 27 4
gpt4 key购买 nike

尝试从微服务内部连接数据库,连接数据库失败

错误:连接 ECONNREFUSED 172.18.0.2:3306

服务/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

最佳答案

可能您使用的 MySQL 版本不支持您正在尝试的登录。尝试使用 mysql v5.7:

docker run -d -p 6603:3306 --name mysql-container -e MYSQL_ROOT_PASSWORD=password mysql:5.7

关于mysql - 带有错误 : connect ECONNREFUSED 的 docker mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56255382/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com