Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ESOCKET Connection Error from node js web app to MSSql Database connection #799

Closed
Praveen335 opened this issue Sep 25, 2018 · 31 comments
Closed

Comments

@Praveen335
Copy link

Praveen335 commented Sep 25, 2018

Hi Team,
Currently, we are getting the intermittent connectivity issues from our web app to MsSql frequently when there is more traffic to the service.
Is there any final recommendations on this issue.

Error:
{ ConnectionError: Failed to connect to <>:1433 - Could not connect (sequence)
at Connection.tedious.once.err (D:\home\site\wwwroot\node_modules\mssql\lib\tedious.js:216:17)
at Connection.g (events.js:291:16)
at emitOne (events.js:96:13)
at Connection.emit (events.js:188:7)
at Connection.socketError (D:\home\site\wwwroot\node_modules\tedious\lib\connection.js:699:14)
at D:\home\site\wwwroot\node_modules\tedious\lib\connection.js:590:25
at SequentialConnectionStrategy.connect (D:\home\site\wwwroot\node_modules\tedious\lib\connector.js:153:9)
at Socket.onError (D:\home\site\wwwroot\node_modules\tedious\lib\connector.js:169:16)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
code: 'ESOCKET',
originalError:

Version Details:
"tedious": "2.0.1",
"mssql": "^4.0.4",

Thanks,
Praveen.

@arthurschreiber
Copy link
Collaborator

Hey @Praveen335 👋🏻

I‘m sorry to hear that you are facing this problem when using tedious. Unfortunately, the information you provided is not enough for us to understand what is happening. Could you provide more information? E.g. it would be helpful for us to know:

  • which version of tedious are you using exactly?
  • when does this error happen exactly? From the stacktrace it looks like this happens when connecting to the database, but can other processes still connect at the same time? I’m thinking this might be a SQLServer issue (maybe due to the high load you mentioned) and not an issue with tedious itself.

Thanks! 🙇🏻‍♂️

@Praveen335
Copy link
Author

Hi @arthurschreiber ,
Thanks for your quick response. I have already updated the tedious version in my post.

Version Details:
"tedious": "2.0.1",
"mssql": "^4.0.4",

We had a look at active work thread to SQL server and network connectivity by raising it to Microsoft support. They mentioned all good from SQLServer end. The work thread percentage also less. I have tried to retry with custom logic. But no luck. After getting socket error, it is continuously throwing for all the subsequent requests. Any suggestion or recommendation would really help us. Currently, we are using the connection pool to connect to the Database.

Thanks,
Praveen.

@regevbr
Copy link

regevbr commented Oct 1, 2018

Same here, it suddnely gets to that state and gets stuck...

@TimTilroy
Copy link

TimTilroy commented Dec 18, 2018

We are also seeing the same connection errors happening on our system.

We are connecting a connectionPool on service start.
new App.SQL.ConnectionPool

At a random moment a request fails with:

ConnectionError: Failed to connect to databaseserver:1433 - Could not connect (sequence)

Service restarts automatically but keeps throwing these errors for about 20 minutes. After that service restarts and it can connect again.

We are seeing this with multiple node processes on this server but they are not going down simultaneously (sometimes they do), which is kinda weird. We believe the cause is in the NodeJS app and not in the mssql DB.

We are using these versions:

mssql: 4.3.0 (latest)
tedious version included in this package is 2.7.1.

@MarioPerezEsteso
Copy link

Hi. We are also experiencing this issue.

These are our versions:
mssql: 4.3.0
which uses tedious version: 2.7.1

ConnectionError: Failed to connect to xxxxxx.database.windows.net:1433 in 15000ms
at Connection.tedious.once.err (...node_modules\mssql\lib\tedious.js:239:17)
at Object.onceWrapper (events.js:315:30)
at emitOne (events.js:116:13)
at Connection.emit (events.js:211:7)
at Connection.connectTimeout (...node_modules\mssql\node_modules\tedious\lib\connection.js:944:12)
at Timeout._onTimeout (...node_modules\mssql\node_modules\tedious\lib\connection.js:913:16)
at ontimeout (timers.js:482:11)
at tryOnTimeout (timers.js:317:5)
at Timer.listOnTimeout (timers.js:277:5)

@sergeos
Copy link

sergeos commented Mar 7, 2019

Write your versions of MSSQL Server. Now, SQLNCLI11 is replaced by MSOLEDBSQL for MSSQL2017 instance.
https://blogs.msdn.microsoft.com/sqlnativeclient/2018/03/30/released-microsoft-ole-db-driver-for-sql-server/

@raygift
Copy link

raygift commented Apr 10, 2019

got same error when using code copied from microsoft official sample: https://www.microsoft.com/en-us/sql-server/developer-get-started/node/windows/step/2.html

Finally, i solved this error by enable TCP/IP protocol in "Sql Server Configuration Manager"->"SQL Server Network Configuration"->" Protocols for "->"TCP/IP"

C:\Users\zpc\Desktop\SqlServerSample>node connect.js { ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence) at ConnectionError (C:\Users\zpc\Desktop\SqlServerSample\node_modules\tedious\lib\errors.js:13:12) at Connection.socketError (C:\Users\zpc\Desktop\SqlServerSample\node_modules\tedious\lib\connection.js:1183:28) at Connector.execute (C:\Users\zpc\Desktop\SqlServerSample\node_modules\tedious\lib\connection.js:1022:21) at SequentialConnectionStrategy.connect (C:\Users\zpc\Desktop\SqlServerSample\node_modules\tedious\lib\connector.js:69:7) at Socket.onError (C:\Users\zpc\Desktop\SqlServerSample\node_modules\tedious\lib\connector.js:84:12) at Socket.emit (events.js:189:13) at emitErrorNT (internal/streams/destroy.js:82:8) at emitErrorAndCloseNT (internal/streams/destroy.js:50:3) at process._tickCallback (internal/process/next_tick.js:63:19) message: 'Failed to connect to localhost:1433 - Could not connect (sequence)', code: 'ESOCKET' }

@JoyEnergiser
Copy link

got same error when using code copied from microsoft official sample: https://www.microsoft.com/en-us/sql-server/developer-get-started/node/windows/step/2.html

Finally, i solved this error by enable TCP/IP protocol in "Sql Server Configuration Manager"->"SQL Server Network Configuration"->" Protocols for "->"TCP/IP"

C:\Users\zpc\Desktop\SqlServerSample>node connect.js { ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence) at ConnectionError (C:\Users\zpc\Desktop\SqlServerSample\node_modules\tedious\lib\errors.js:13:12) at Connection.socketError (C:\Users\zpc\Desktop\SqlServerSample\node_modules\tedious\lib\connection.js:1183:28) at Connector.execute (C:\Users\zpc\Desktop\SqlServerSample\node_modules\tedious\lib\connection.js:1022:21) at SequentialConnectionStrategy.connect (C:\Users\zpc\Desktop\SqlServerSample\node_modules\tedious\lib\connector.js:69:7) at Socket.onError (C:\Users\zpc\Desktop\SqlServerSample\node_modules\tedious\lib\connector.js:84:12) at Socket.emit (events.js:189:13) at emitErrorNT (internal/streams/destroy.js:82:8) at emitErrorAndCloseNT (internal/streams/destroy.js:50:3) at process._tickCallback (internal/process/next_tick.js:63:19) message: 'Failed to connect to localhost:1433 - Could not connect (sequence)', code: 'ESOCKET' }

Thank you! I was having this exact issue ;)

@TimTilroy
Copy link

TimTilroy commented Jul 29, 2019

Since we are still experiencing this issue with almost all of our nodejs services we did some extra tests.
The comment above with the TCP/IP fix was already enabled on our sql server.

We created a new nodejs service that is doing absolutely nothing. It is not called by another service, just runs in PM2.
It will open a new connectionpool when it starts and just sits there.

We got 3 errors in 5 days, happening randomly:
"ConnectionError: Failed to connect to sql.tilroy.internal:1433 - Could not connect (sequence)".

This is the code:

`
const config = {
user: Config.sql.sqluser,
password: Config.sql.sqlpassword,
server: Config.sql.sqlhost,
database: Config.sql.sqldatabase,
port: Config.sql.sqlport,
connectionTimeout: 3000,
requestTimeout: 3000,
pool: {
max: 100,
min: 1, //don't close all the connections.
idleTimeoutMillis: 1000,
evictionRunIntervalMillis: 1500000
}
};

const sqlConnection = new SQL.ConnectionPool(config, function (err) {
    Log.debug("got sql connection");
	if(err){
		Log.error(err);
		process.exit(1);
	}
});

sqlConnection.on('error', err => {
    Log.error(`Connection err : ${err}`);
    process.exit(1);
});

`

We upgraded our SQL server but that didn't help. Updated all our packages but still got these errors.
Anything else we can try? We'd rather not throw out tedious/mssql as we use it in quite a lot of services.

@IanChokS
Copy link
Member

IanChokS commented Aug 7, 2019

@TimTilroy are you using tedious to handle your connection pool or the tedious-connection-pool? If you're using the tedious project, maybe you can try the tedious-connection-pool one and see if that helps.

@TimTilroy
Copy link

Hi IanChokS,

We are not using the tedious-connection-pool package, but the default connectionPool of the mssql package (its using tedious I believe).

However we have updated the mssql package to version 5.1 now and it seems stable, we've got no more connection errors on our test service. One of the changes is the following:

Moved pool library from node-pool to tarn.js

So maybe that fixed our problem.

We also set the min pool connections to 0, don't know if that could have any effect.

@IanChokS
Copy link
Member

IanChokS commented Aug 8, 2019

@MarioPerezEsteso if you're having trouble connecting to your server, you can try to make sure that TCP IP is enabled and that You have the correct port number in your configuration to check if the server is reachable.

@regevbr, @Praveen335 If you're using connection pooling, you can try and use the tarn.js library instead of the node-pool like what TimTilroy did to see if it fixes your connection issues. If not, perhaps try upgrading to the latest mssql (v5.1).

@TimTilroy
Copy link

Update: we have applied the new version of mssql (5.1.0) to all our sql services, updated the min pool connections to 0 and it looks like the connection errors stopped since our deploy.

@MohamedAla
Copy link

I think the problem is just because you are using " / " instead of " \ " in the name or smthing like that

@IanChokS
Copy link
Member

@Praveen335 Have you tried upgrading to the new version of mssql (5.1.0) to see if it resolves your issue? If not, feel free to re-open this issue.

@achaugule
Copy link

I'm using versions:
mssql: "^6.2.0",
tedious: "^8.3.0"

I have enabled TCP/IP in configuration manager. Also all my sql services are running. yet am getting following error:

C:\Nodejs\node-sql-conn\Database>node connect.js
tedious deprecated In the next major version of tedious, creating a new Connection instance will no longer establish a connection to the server automatically. Please use the new connect helper function or call the .connect method on the newly created Connection object to silence this message. internal\process\task_queues.js:79:11
Connection Failed

C:\Nodejs\node-sql-conn\Database\connect.js:26
throw err;
^
ConnectionError: Failed to connect to localhost:undefined - Cannot call write after a stream was destroyed
at ConnectionError (C:\Nodejs\node-sql-conn\node_modules\tedious\lib\errors.js:13:12)
at Connection.socketError (C:\Nodejs\node-sql-conn\node_modules\tedious\lib\connection.js:1308:56)
at Socket. (C:\Nodejs\node-sql-conn\node_modules\tedious\lib\connection.js:1143:14)
at Socket.emit (events.js:327:22)
at errorOrDestroy (internal/streams/destroy.js:108:12)
at onwriteError (_stream_writable.js:418:5)
at onwrite (_stream_writable.js:445:5)
at doWrite (_stream_writable.js:399:11)
at writeOrBuffer (_stream_writable.js:387:5)
at Socket.Writable.write (_stream_writable.js:318:11) {
code: 'ESOCKET'
}

This is my Code:
var Connection = require('tedious').Connection;
var config = {
server: 'localhost',
authentication: {
type: 'default',
options: {
userName: 'sa',
password: '####',
port:1433
}
},
options: {
database: 'Company',
instanceName: 'MSSQLSERVER',
rowCollectionOnDone: true,
useColumnNames: false,
trustServerCertificate: false
}
};
var connection = new Connection(config);
connection.on('connect',function(err){
if(err){
console.log('Connection Failed');
throw err;
}
else{
console.log('Connected');
}
});
module.exports = connection;

@Nipont
Copy link

Nipont commented Jul 13, 2020

got same error when using code copied from microsoft official sample: https://www.microsoft.com/en-us/sql-server/developer-get-started/node/windows/step/2.html

Finally, i solved this error by enable TCP/IP protocol in "Sql Server Configuration Manager"->"SQL Server Network Configuration"->" Protocols for "->"TCP/IP"
SQLServerConfigurationManager

C:\Users\zpc\Desktop\SqlServerSample>node connect.js { ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence) at ConnectionError (C:\Users\zpc\Desktop\SqlServerSample\node_modules\tedious\lib\errors.js:13:12) at Connection.socketError (C:\Users\zpc\Desktop\SqlServerSample\node_modules\tedious\lib\connection.js:1183:28) at Connector.execute (C:\Users\zpc\Desktop\SqlServerSample\node_modules\tedious\lib\connection.js:1022:21) at SequentialConnectionStrategy.connect (C:\Users\zpc\Desktop\SqlServerSample\node_modules\tedious\lib\connector.js:69:7) at Socket.onError (C:\Users\zpc\Desktop\SqlServerSample\node_modules\tedious\lib\connector.js:84:12) at Socket.emit (events.js:189:13) at emitErrorNT (internal/streams/destroy.js:82:8) at emitErrorAndCloseNT (internal/streams/destroy.js:50:3) at process._tickCallback (internal/process/next_tick.js:63:19) message: 'Failed to connect to localhost:1433 - Could not connect (sequence)', code: 'ESOCKET' }

This one work for me. Thank you for give me the solution.

@fedecaccia
Copy link

Im also experimenting this ESOCKET connection errors, and the issue is not related with TCP/IP since the app is connected from AWS EC2 to AS RDS and it is working most of the time.

@fedecaccia
Copy link

FINALLY I solved the error. The script I was using each time I requested a new connection:

function getConnection () {
    // console.log("config")
    // console.log(config)
    return new Promise(function (resolve, reject) {
        const pool = new sql.ConnectionPool(getConfig())
        // console.log("Getting connection...");
        pool.connect()
        .then((cn) => {
            // console.log("connection got");
            resolve(cn);
        })
        .catch((e) => {
            // console.log("connection not got");
            reject(e);
        });
    })
}

The script that solved the issue:


function runCommand(cmdText) {
    return new Promise((resolve, reject) => {
        pool2Connect
        .then((pool) => {
            // pool.request() // or: new sql.Request(pool2)
            // .input('input_parameter', sql.Int, 10)
            // .output('output_parameter', sql.VarChar(50))
            // .execute('procedure_name', (err, result) => {
            //     // ... error checks
            //     console.dir(result)
            // })
            pool.request() // or: new sql.Request(pool2)
            .query(cmdText)
            .then((rows) => {
                return resolve(rows.recordset);
            })
            .catch((e) => {
                return reject(e);
            });
        })
        .catch((err) => {
            return reject(err);
        });
    });
}

where pool2Connect needs to be defined initially, when starting the script:

    pool2 = new sql.ConnectionPool(config);
    pool2Connect = pool2.connect();
    pool2.on('error', err => {
        console.log(err);
    });

Hope it helps

@Vasanthi0205
Copy link

Hi,
I am connecting to Azure Data Studio server from Node.js using tedious. (not using pool connection of tedious)
I am facing this ESOCKET error randomly.
My Version:
tedious: 12.3.0.

Please provide me a solution to resolve this

@edwinspire
Copy link

edwinspire commented Dec 9, 2021

I find myself with the same novelty, I connect without using pool, I do it to about 1000 different servers and of those 5 they present that message, it is not a TCP issue.
For the servers that do not connect I have an additional observation, using the same application but from Windows if they connect, but when I upload to the production server, a Centos 7, the connection is not made, but only on these few servers.
What else could you see?

@abdulhadi-tcp
Copy link

This did the trick for me after trying 99% of the solutions I found online:
https://stackoverflow.com/questions/61484005/timeout-error-while-connecting-to-sql-server-connection-error-failed-to-connec

@gretchunkim
Copy link

I was getting the exact same error message and confirmed it wasn't TCP/IP issue. Mine turned out to be account user setting/policy issue on SQL. I've switced to another account assigned to SQL and it started to connect.

@ramses429
Copy link

image
image
image
image

Use how host your own public ip direction

@nickpazfernande
Copy link

After several days with this problem, I found a blog that said to use the dynamic port. And it worked!!!
Captura de pantalla 2022-05-09 090840

@MuraliPagadalaColibri
Copy link

MuraliPagadalaColibri commented Sep 1, 2022

Ttrying to connect to sql server database, giving following below error, please help on this error.

ConnectionError: Failed to connect to "AWS SQL Server Database" - getaddrinfo ENOTFOUND
at Connection.socketError (C:\Scraper\CEShop\node_modules\tedious\lib\connection.js:1399:28)
at C:\Scraper\CEShop\node_modules\tedious\lib\connection.js:1180:14
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
code: 'ESOCKET',
isTransient: undefined
}

@mShan0
Copy link
Contributor

mShan0 commented Sep 1, 2022

Hi @MuraliPagadalaColibri, can you open a new issue? We can help you from there.

@MeghaGhotkar13
Copy link

Since we are still experiencing this issue with almost all of our nodejs services we did some extra tests. The comment above with the TCP/IP fix was already enabled on our sql server.

We created a new nodejs service that is doing absolutely nothing. It is not called by another service, just runs in PM2. It will open a new connectionpool when it starts and just sits there.

We got 3 errors in 5 days, happening randomly: "ConnectionError: Failed to connect to sql.tilroy.internal:1433 - Could not connect (sequence)".

This is the code:

` const config = { user: Config.sql.sqluser, password: Config.sql.sqlpassword, server: Config.sql.sqlhost, database: Config.sql.sqldatabase, port: Config.sql.sqlport, connectionTimeout: 3000, requestTimeout: 3000, pool: { max: 100, min: 1, //don't close all the connections. idleTimeoutMillis: 1000, evictionRunIntervalMillis: 1500000 } };

const sqlConnection = new SQL.ConnectionPool(config, function (err) {
    Log.debug("got sql connection");
	if(err){
		Log.error(err);
		process.exit(1);
	}
});

sqlConnection.on('error', err => {
    Log.error(`Connection err : ${err}`);
    process.exit(1);
});

`

We upgraded our SQL server but that didn't help. Updated all our packages but still got these errors. Anything else we can try? We'd rather not throw out tedious/mssql as we use it in quite a lot of services.

@MeghaGhotkar13
Copy link

Hey @TimTilroy
Thanks for sharing it helped me
Finally, I solved this error by enabling TCP/IP protocol in "SQL Server Configuration Manager"->"SQL Server Network Configuration"->" Protocols for "->" TCP/IP"

@ShahriarKh
Copy link

For debugging, I tried to login with Azure Data Studio and got this mesaage:
image

All I had to do was adding encrypt: false. This might not be the best solution, but I hope it helps future Googlers.

@protoid2
Copy link

For debugging, I tried to login with Azure Data Studio and got this mesaage: image

All I had to do was adding encrypt: false. This might not be the best solution, but I hope it helps future Googlers.

but for me ,thats solve thanks brother..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests