I have the docker-compose.yml:
version: "3.7"
services:
app:
build: .
ports:
- 3000:3000
working_dir: /app
volumes:
- ./:/app
depends_on:
- db
db:
image: "mcr.microsoft.com/mssql/server:2019-latest"
ports:
- 1433:1433
environment:
SA_PASSWORD: "Thieu@098551298"
ACCEPT_EULA: "Y"
volumes:
- mssql-data:/var/opt/mssql
volumes:
mssql-data:
file Dockerfile:
FROM node:12-alpine
ENV NODE_ENV=production
WORKDIR /app
COPY ["package.json", "package-lock.json*", "./"]
RUN npm install --production
COPY . .
CMD [ "node", "server.js" ]
file server.js:
var express = require("express");
var app = express();
var { ExecuteSQL } = require("./sql");
app.get("/", async (req, res) => {
var s = await ExecuteSQL("select *from post");
res.send(s.recordset);
});
app.listen(3000, () => console.log("listening on port 3000"));
And sql.js:
var sql = require("mssql");
var config = {
user: "sa",
password: "Thieu@098551298",
server: "localhost",
database: "blog",
options: {
enableArithAbort: true,
trustServerCertificate: true,
},
};
function ExecuteSQL(query) {
return new Promise((resolve, reject) => {
sql.connect(config, (err, db) => {
if (err) reject(err);
var request = new sql.Request();
request.query(query, (err, db) => {
if (err) reject(err);
resolve(db);
});
});
});
}
async function z() {
var z = await ExecuteSQL("select *from post");
console.log(z.recordsets);
}
z();
module.exports = {
ExecuteSQL: ExecuteSQL,
};
Step 1: I run this cmd: docker-compose up -d (That will running two container db and app)
Step 2: I open browser go to http://localhost:3000/ (My goal is the browser will show the recordset when i select *from post from the server.js file) but it will throw err:
UnhandledPromiseRejectionWarning: ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
But when I run cmd: node sql - It can connect to SQL Server in the container and show data because I have the function for test in sql.js
:
async function z() {
var z = await ExecuteSQL("select *from post");
console.log(z.recordsets);
}
z();
Data show:
[
[
{
id: 1,
title: 'How to learn docker',
content: ' qjweqwn ejqwne qwne nqwje nqwjen qjwne ojqwne jqwn'
},
{
id: 2,
title: 'How to learn english',
content: ' qwen qwen qjen qw'
}
]
]
I have provided the necessary information, so is there any way for the app container to connect to the db container and get the data? Maybe I should edit something more in the docker-compose.yml file?
CodePudding user response:
You gave wrong sever address. Never forget "localhost" in dockers means inside that docker.
To fix this config sever address "db"