容器无法连接到 docker-compose 中的 Microsoft SQL Server



我有docker-compose。包含两个服务的Yml文件:

  • 一个NodeJs API
  • microsoft mssql数据库

docker-compose.yml:

version: "3.7"
services:
api:
container_name: dev_api
environment:
- DATABASE_PUBLIC_URL=${DATABASE_URL} # Not used yet
build: .
restart: always
ports:
- "4100:4100"
networks:
- backend
depends_on:
- db
db:
image: mcr.microsoft.com/mssql/server:2017-latest
restart: always
ports:
- "1433:1433"
environment:
ACCEPT_EULA: "Y"
SA_PASSWORD: "Abc123**"
networks:
- backend
networks:
backend:
driver: bridge

当我用docker-compose up运行它时,我得到:

...
021-10-22 14:54:20.77 spid11s     The tail of the log for database model is being rewritten to match the new sector size of 4096 bytes.  2048 bytes at offset 75776 in file /var/opt/mssql/data/modellog.ldf will be written.
dev_api |   App is running at http://localhost:4100 in development mode
dev_api |   Press CTRL-C to stop
dev_api |
dev_api | ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
dev_api |     at /usr/src/app/node_modules/mssql/lib/tedious/connection-pool.js:71:17
dev_api |     at Connection.onConnect (/usr/src/app/node_modules/tedious/lib/connection.js:1043:9)
dev_api |     at Object.onceWrapper (node:events:510:26)
dev_api |     at Connection.emit (node:events:390:28)
dev_api |     at Connection.emit (/usr/src/app/node_modules/tedious/lib/connection.js:1071:18)
dev_api |     at Connection.socketError (/usr/src/app/node_modules/tedious/lib/connection.js:1669:12)
dev_api |     at /usr/src/app/node_modules/tedious/lib/connection.js:1428:21
dev_api |     at SequentialConnectionStrategy.connect (/usr/src/app/node_modules/tedious/lib/connector.js:129:14)
dev_api |     at Socket.onError (/usr/src/app/node_modules/tedious/lib/connector.js:149:12)
dev_api |     at Socket.emit (node:events:390:28) {
dev_api |   code: 'ESOCKET',
dev_api |   originalError: ConnectionError: Failed to connect to localhost:1433 - Could not 
dev_api | }
2021-10-22 14:54:20.80 spid5s      Converting database 'msdb' from version 862 to the current version 869.
2
...

我可以从htpp://localhost:4100访问应用程序,但我得到错误,因为我不能访问数据库


编辑

工程中有一个文件ormconfig.json,需要修改数据库主机

你应该配置你的API,使用DNS名称与Docker Compose网络中的MSSQL实例通信。像下面的

api:
container_name: dev_api
environment:
- DATABASE_PUBLIC_URL=db

注意您的MSSQL容器实例被命名为db

当容器试图访问localhost时,就像任何其他机器一样,它试图与自己通信。在您的示例中,Node API容器上没有运行MSSQL,因此它将失败。

在Docker Compose网络中,使用服务名或自定义主机名与其他容器通信。

相关内容

  • 没有找到相关文章

最新更新