I have docker-compose.yml file with two services:
- a NodeJs API
- a microsoft mssql database
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
when I run it with docker-compose up
, I get :
...
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
...
I can access the application from htpp://localhost:4100
, but I get error since I can't access the database
Edit
In the project, there is a file ormconfig.json
, the database host needs to be changed.
CodePudding user response:
You should be configuring your API to communicate with the MSSQL instance within the Docker Compose network using DNS names. Like below
api:
container_name: dev_api
environment:
- DATABASE_PUBLIC_URL=db
Note your MSSQL container instance is named db
.
When a container tries to access localhost
, just like any other machine it's trying to communicate with itself. In your case, the Node API container will not have MSSQL running on it, so it will fail.
Within Docker Compose networks, use the service name or a custom host name to communicate with other containers.