我有一个Node应用程序的Docker容器,该容器连接到MySQL数据库。该数据库位于容器外部的本地主机中。
首先,我尝试通过命令docker run -p 3010:80 nigel/insideroil
运行它。该过程正常启动,编译了所有内容,但是当应用程序尝试连接到数据库时,出现以下错误:
Unhandled rejection SequelizeBaseError: connect ECONNREFUSED 127.0.0.1:3306
at Handshake.<anonymous> (/usr/src/insider_oil/server/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:80:20)
at Handshake.<anonymous> (/usr/src/insider_oil/server/node_modules/mysql/lib/Connection.js:502:10)
at Handshake._callback (/usr/src/insider_oil/server/node_modules/mysql/lib/Connection.js:468:16)
at Handshake.Sequence.end (/usr/src/insider_oil/server/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24)
at Protocol.handleNetworkError (/usr/src/insider_oil/server/node_modules/mysql/lib/protocol/Protocol.js:361:14)
at Connection._handleNetworkError (/usr/src/insider_oil/server/node_modules/mysql/lib/Connection.js:420:18)
at emitOne (events.js:96:13)
at Socket.emit (events.js:189:7)
at emitErrorNT (net.js:1280:8)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickDomainCallback (internal/process/next_tick.js:122:9)
在研究中,我发现该错误可能与外部端口的访问有关,如此链接https://docs.docker.com/config/containers/container-networking/#published-ports所述。
因此,我尝试运行该命令,并传递另一个参数,例如:docker run -p 3010:80 -p 127.0.0.1:3306:3306 nigel/insideroil
。但是,现在的错误是:
docker: Error response from daemon: driver failed programming external connectivity on endpoint cocky_wilson (c702c7f659ee766ba11993ed6b2c3ce851f6a6cced3d2c04a31bb578a11b2b40): Error starting userland proxy: Bind for 127.0.0.1:3306 failed: port is already allocated.
ERRO[0000] error waiting for container: context canceled
感谢您的帮助。预先感谢
答案 0 :(得分:0)
如果要从容器访问主机上的端口,则应使用主机IP地址(而不是127.0.0.1)。当然,DB也应该侦听主机IP地址(不是127.0.0.1)。
或者也可以在容器内运行数据库,并通过名称使用直接连接。