Can't access mysql container from node but fro

2019-08-16 09:16发布

I created a node application that is run by a docker-compose. The application needs a mysql server which is also started but when I get to the point in my node application to access the server I get the following error:

events.js:136
throw er; // Unhandled 'error' event
^ 
Error: connect ECONNREFUSED 127.0.0.1:3306
 at Object._errnoException (util.js:1031:13)
 at _exceptionWithHostPort (util.js:1052:20)
 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1195:14)
 --------------------
 at Protocol._enqueue (/usr/src/node_modules/mysql/lib/protocol/Protocol.js:145:48)
 at Protocol.handshake (/usr/src/node_modules/mysql/lib/protocol/Protocol.js:52:23)
 at Connection.connect (/usr/src/node_modules/mysql/lib/Connection.js:130:18)
 at Connection._implyConnect (/usr/src/node_modules/mysql/lib/Connection.js:461:10)
 at Connection.query (/usr/src/node_modules/mysql/lib/Connection.js:206:8)
 at Object.<anonymous> (/usr/src/configs/passport.js:15:12)
 at Module._compile (module.js:641:30)
 at Object.Module._extensions..js (module.js:652:10)
 at Module.load (module.js:560:32)
 at tryModuleLoad (module.js:503:12)
 at Function.Module._load (module.js:495:3)
 at Module.require (module.js:585:17)
 at require (internal/module.js:11:18)
 at Object.<anonymous> (/usr/src/app.js:47:1)
 at Module._compile (module.js:641:30)
 at Object.Module._extensions..js (module.js:652:10)

The corresponding node code is essentially this:

var mysql = require('mysql');
var dbconfig = require('./database');
var connection = mysql.createConnection(dbconfig.connection);

And database.js looks like this:

module.exports = {
  'connection': {
    'host': '127.0.0.1',
    'user': 'user',
    'password': 'password'
  },
  'database': 'website_user',
  'users_table': 'users'
};

All of this is run lokally on my MacBook. When I open a second terminal window and execute:

mysql -h 127.0.0.1 -u user -p

I can successfully connect to this server. The user specified there is identical to the user that is passed to my connection establishment in the node app. I've messed around with this for probably 4 hours now and have no idea what I'm doing wrong. What do I have to change in order for this to work?

Let me know if there is anything I need to provide in order to help me with my problem. Thanks!

1条回答
不美不萌又怎样
2楼-- · 2019-08-16 10:13

You are trying to connect to 127.0.0.1:3306 from the node container - but that's the node container itself. If your database service is named mysql you should be able to use a config like this (assuming docker-compose.yml version 2 or above):

module.exports = {
  'connection': {
    'host': 'mysql',
    'user': 'user',
    'password': 'password'
  },
  'database': 'website_user',
  'users_table': 'users'
};
查看更多
登录 后发表回答