web docker file
FROM node:14
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"
db docker file
FROM mcr.microsoft.com/mssql/server:2019-latest
EXPOSE 1433
docker compose file
version: "3.8"
services:
db:
build: ./db
environment:
SA_PASSWORD: mahe@123
ACCEPT_EULA: Y
MSSQL_PID: Developer
ports:
- "1433:1433"
restart: always
web:
build: ./web
environment:
DB_CONNECTION_STRING: Server=localhost;Database=Bitespeed;User Id=sa;Password=mahe@123;
ports:
- "3000:3000"
depends_on:
- db
restart: on-failure
dbconfig.js file
const config = {
user: 'sa',
password: 'mahe@123',
server: 'localhost',
database: 'Bitespeed',
options: {
enableArithAort: true,
trustServerCertificate:true
},
port: 1433
}
module.exports = config;
server.js file
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const sql = require('mssql');
const config = require("./dbconfig")
require('dotenv').config()
const port = process.env.PORT
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
const mainRouter = require('./router')
app.use('/api',mainRouter)
function connectWithRetry(){
return sql.connect(config,(err) => {
if (err) {
console.log(`Connection to DB failed, retry in 5s `,err.message)
sql.close()
setTimeout(connectWithRetry(), 5000);
}
else {
console.log('Connected to SQL Server successfully');
}
});
}
connectWithRetry()
app.listen(port , ()=>{
console.log("app is listening on port " + port)
})
can any plase help me what is the error. and i am getting the following error
and my db is running fine.. enter image description here
can any one help me with this..
i am expecting my node app will connect to the sql server.
1条答案
按热度按时间tf7tbtn21#
In your case,
localhost
will point to the container itself (web
). You can specify the docker-compose alias of the database service (db
) instead in your config:Since you are also setting an environment variable
DB_CONNECTION_STRING
in yourdocker-compose.myml
which seems to overwrite your settings, you probably also need to change the "localhost" in that environment variable: