Node app not connecting to MySQL database in docker, using links - javascript

Trying to connect my node app to mysql database. I already have an express api set up that manages to connect but for some reason node doesn't work. Using "links" in the docker compose file, and it resolves to the right local (internal) container IP but still doesn't connect. Error:
The node app isn't listening on any ports itself (does it need to?). Thanks!
Error: connect ECONNREFUSED 192.168.64.2:3306
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1278:16) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '192.168.64.2',
port: 3306,
fatal: true
}
let con;
async function create_connection() {
const username = await process.env.USERNAME;
const password = await process.env.PASSWORD;
con = await mysql.createConnection({
host: "db",
user: username,
password: password,
database: "database",
port: "3306",
});
await con.connect(function(err) {
if (err) throw err;
});
}
create_connection();
docker-compose:
version: '3.8'
services:
db:
image: mysql:8.0.31
cap_add:
- SYS_NICE
restart: always
env_file:
- somefile.env
ports:
- 127.0.0.1:external_port:3306
volumes:
- db:/var/lib/mysql
- ./db/init.sql:/docker-entrypoint-initdb.d/init.sql
express:
image: express/someapi
links:
- db:db
ports:
- 127.0.0.1:external_port:3355
env_file:
- somefile.env
depends_on:
- db
node_app:
image: some_image
links:
- db:db
env_file:
- somefile.env
depends_on:
- db
volumes:
db:
driver: local
~
Tried using links and mysql2 to connect to the database. Expected it to work as with my express backend but does not connect.

Related

Connection between MariaDB and NodeJS not working

I'm using a vServer from Ionos for a little project. I installed a MariaDB and NodeJS. Currently I'm trying to connect them both. Here is my code:
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: 'localhost',
user:'root',
password: 'xxxxxxxxx',
database: 'christmastrees',
connectionLimit: 5,
});
async function asyncFunction() {
let conn;
try {
conn = await pool.getConnection();
const rows = await conn.query("SELECT * from bäume");
console.log(rows); //[ {val: 1}, meta: ... ]
} catch (err) {
throw err;
} finally {
if (conn) return conn.end();
}
}
But when executing the file (node app), I get an error message after a few seconds
Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1157:16)
From event:
at _registerHandshakeCmd (/root/server/node_modules/mariadb/lib/connection.js:745:11)
at /root/server/node_modules/mariadb/lib/connection.js:57:11
at new Promise (<anonymous>)
at Connection.connect (/root/server/node_modules/mariadb/lib/connection.js:56:16)
at createConnectionPoolPromise (/root/server/node_modules/mariadb/lib/pool-promise.js:31:8)
at creationTryout (/root/server/node_modules/mariadb/lib/pool-base.js:373:9)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true
}
So I searched for help and after 2 hours I literally found only one Idea. I added this line of code to my connection...
port: '/var/run/mysqld/mysqld.sock'
I tryed again to use node app, but this time I didn't get an error message, it is loading forever and nothing happens.
I would be so grateful for any help...
So I found the solution to my problem.
I checked if my MariaDB Service is even running and no it wasn't ^^

[SequelizeConnectionRefusedError]: connect ECONNREFUSED 127.0.0.1:3306

Hi I am new with Sequelize ORM. I am following some tutorial and while hands-on, I am facing the problem in connecting the MySQL database with server.
ConnectionRefusedError [SequelizeConnectionRefusedError]: connect ECONNREFUSED 127.0.0.1:3306
at ConnectionManager.connect (G:\projects\chatApp\node_modules\sequelize\lib\dialects\mysql\connection-manager.js:116:17)
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
parent: Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16) {
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true
},
original: Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16) {
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true
}
}
Serve.js
const { ApolloServer } = require('apollo-server')
const { sequelize } = require('./models')
const resolvers = require('./graphql/resolvers')
const typeDefs = require('./graphql/typeDefs')
const server = new ApolloServer({
typeDefs,
resolvers,
})
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`)
sequelize
.authenticate()
.then(() => console.log('Database connected!!'))
.catch((err) => console.log(err))
})
config.json
{
"development": {
"username": "root",
"password": "root",
"database": "database_dev",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
Can anyone tell me why I am not able to connect to the database?
run MySql installer
reconfigure the MySql Server. it will work fine.
check this out
Check port of mysql you are using, maybe 3307 ?

Docker call from node container to python container

I've got a Docker project composed by:
Rest API written in Flask (called "python")
Backend written in nodejs (called "server")
Mongodb
#docker-compose.yml
version: '3.8'
services:
server:
build:
context: ./server
dockerfile: ./Dockerfile
restart: on-failure
ports:
- "6000:6000"
links:
- python
- mongo
depends_on:
- python
- mongo
volumes:
- ./server:/code
env_file: .env
environment:
- MONGO_USERNAME=$DATABASE_USERNAME
- MONGO_PASSWORD=$DATABASE_PASSWORD
- MONGO_HOST=mongo
- MONGO_PORT=$DATABASE_PORT
- MONGO_DB=$DATABASE
networks:
- todo-network
python:
build:
context: ./rest_api_wrapper_py
dockerfile: ./Dockerfile
restart: on-failure
ports:
- "5000:5000"
links:
- mongo
depends_on:
- mongo
volumes:
- ./rest_api_wrapper_py:/code
env_file: .env
environment:
- MONGO_USERNAME=$DATABASE_USERNAME
- MONGO_PASSWORD=$DATABASE_PASSWORD
- MONGO_HOST=mongo
- MONGO_PORT=$DATABASE_PORT
- MONGO_DB=$DATABASE
networks:
- todo-network
mongo:
image: mongo
restart: on-failure
env_file: .env
environment:
- MONGO_INITDB_ROOT_USERNAME=$DATABASE_ROOT_USERNAME
- MONGO_INITDB_ROOT_PASSWORD=$DATABASE_ROOT_PASSWORD
- MONGO_INITDB_DATABASE=$DATABASE
- DATABASE_USERNAME=$DATABASE_USERNAME
- DATABASE_PASSWORD=$DATABASE_PASSWORD
- MONGO_PORT=$DATABASE_PORT
volumes:
- /home/s0n1c/tmp/mongo:/data/mongo
- ./docker_scripts/:/docker-entrypoint-initdb.d
- /data/mongodb/db:/data/db
ports:
- "27017:27017"
networks:
- todo-network
networks:
todo-network:
driver: bridge
"python" starts correctly:
Running on http://127.0.0.1:5000/
I need to call the endpoint python:5000/variables from "server" (node js):
(async () => {
try {
const res = await superagent.get('http://python:5000/variables');
console.log(res);
} catch (err) {
console.error(err);
}
})();
This request fails:
server_1 | Error: connect ECONNREFUSED 172.19.0.3:5000
server_1 | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16) {
server_1 | errno: -111,
server_1 | code: 'ECONNREFUSED',
server_1 | syscall: 'connect',
server_1 | address: '172.19.0.3',
server_1 | port: 5000,
server_1 | response: undefined
server_1 | }
Can someone help me, please? Thanks a lot

Connect ssh server through nodejs code with ssh key and server name

I have vpn access, so i can ssh to server by following command from terminal
ssh qa-trinath01.my-qa
Its working fine from terminal.
But from nodejs, its not working. my code is
var express = require("express");
var app = express();
var node_ssh = require('node-ssh')
var
ssh = new node_ssh()
ssh.connect({
host: 'qa-trinath01.my-qa',
username: 'tanantham',
port: 27017,
privateKey: '/Users/tanantham/.ssh/id_rsa'
}).then(function() {
console.error('Success: ');
}).catch((error) => {
console.error('ERROR: ', error);
});;
app.listen(3001);
I am getting output as
ERROR: { Error: getaddrinfo ENOTFOUND qa-trinath01.my-qa qa-trinath01.my-qa:27017
at errnoException (dns.js:50:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:92:26)
code: 'ENOTFOUND',
errno: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'qa-trinath01.my-qa',
host: 'qa-trinath01.my-qa',
port: 27017,
level: 'client-socket' }
Can some one suggest the nodejs code to connect to ssh, i have only ssh key and ssh server name details.
ssh key -> /Users/tanantham/.ssh/id_rsa
server name -> qa-trinath01.my-qa
Have you tried to replace 'privateKey' with 'password' and enter your password.
It's probably not the most secure but it normally works.
Unless you have to use your private key from id-rsa
ssh = new node_ssh()
ssh.connect({
host: 'qa-trinath01.my-qa',
username: 'tanantham',
port: 27017,
password: 'YourPasswordHere'
}).then(function() {
console.error('Success: ');
}).catch((error) => {
console.error('ERROR: ', error);
});;
app.listen(3001);

Trouble making nodejs mysql connection

I am trying to make a simple connection between my nodejs server and my mysql db (using Microsoft SQL server manager studio v14), below is my code and the error message appearing in my console window.
here is my code:
var express = require('express');
var app = express();
var sql = require("mssql");
app.get('/', function (req, res) {
// config for your database
var config = {
user: 'superadmin',
password: '***',
server: 'localhost',
database: 'XXX'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from Schools', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
The error I am getting looks like this:
Server is running..
tedious deprecated The default value for `options.encrypt` will change from `false` to `true`. Please pass `false` explicitly if you want to retain current behaviour. node_modules\mssql\lib\tedious.js:212:23
{ ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at Connection.tedious.once.err (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\tedious.js:216:17)
at Object.onceWrapper (events.js:275:13)
at Connection.emit (events.js:182:13)
at Connection.socketError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:1004:14)
at C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:869:25
at SequentialConnectionStrategy.connect (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:154:9)
at Socket.onError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:170:16)
at Socket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
code: 'ESOCKET',
originalError:
{ ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at ConnectionError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\errors.js:12:12)
at Connection.socketError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:1004:30)
at C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:869:25
at SequentialConnectionStrategy.connect (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:154:9)
at Socket.onError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:170:16)
at Socket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at process._tickCallback (internal/process/next_tick.js:174:19)
message: 'Failed to connect to localhost:1433 - Could not connect (sequence)',
code: 'ESOCKET' },
name: 'ConnectionError' }
{ ConnectionError: Connection is closed.
at Request._query (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\base.js:1299:37)
at Request._query (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\tedious.js:497:11)
at Request.query (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\base.js:1242:12)
at C:\Users\smr09\Desktop\Code\ou\db_test\test.js:24:17
at _poolCreate.then.catch.err (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\base.js:269:7)
at process._tickCallback (internal/process/next_tick.js:178:7) code: 'ECONNCLOSED', name: 'ConnectionError' }
I am rather new at this particularly with dealing with databases. Can someone explain what the error means?
Add this line to the config:
options: {
encrypt: false
}
It will finally look like:
var config = {
user: 'superadmin',
password: '***',
server: 'localhost',
database: 'XXX' ,
options: {
encrypt: false
}
};
try to put encrypt: false in your config{}, it will work.
your error:
ConnectionError: Failed to connect to localhost:1433 - Could not
connect (sequence)
My problem was resolved by adding port
var config = {
user: 'superadmin',
password: '***',
server: 'localhost',
database: 'XXX',
port: '',
};

Categories

Resources