Not able to connect a rabbitmq docker with appl docker - node.js

I have a simple app (simple.js), written in nodejs,
var amqp = require('amqplib/callback_api');
amqp.connect('amqp://localhost', function(err, conn) {
conn.createChannel(function(err, ch) {
var q = 'hello';
ch.assertQueue(q, {durable: false});
// Note: on Node 6 Buffer.from(msg) should be used
ch.sendToQueue(q, new Buffer('Hello World!'));
console.log(" [x] Sent 'Hello World!'");
});
setTimeout(function() { conn.close(); process.exit(0) }, 500);
});
And I have dockerized it (simple-app). Then I pulled rabbitmq docker from docker hub.
When I try to link these in following manner :
docker run -d --name rabbitmq-server rabbitmq:latest
docker build -t simple-app .
docker run -d -P --name myapp --link rabbitmq-server:rabbitmq-server simple-app
docker logs a8789193af523b
I get the below mentioned error :
/usr/src/server/simple.js:3
conn.createChannel(function(err, ch) {
^
TypeError: Cannot read property 'createChannel' of undefined
at /usr/src/server/simple.js:3:7
at /usr/src/server/node_modules/amqplib/callback_api.js:16:10
at Socket.<anonymous> (/usr/src/server/node_modules/amqplib/lib/connect.js:167:18)
at Socket.g (events.js:292:16)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at emitErrorNT (net.js:1277:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
I have tried many ways in order to resolve :
1. Exposed all ports with -P option using --links
2. Did mapping of specific ports with -p option --links
3. created network with bridge as driver and used that n/w for starting all my dockers.
None of the above methods seem to work, I am continuosly getting same error.
I am trying this on AWS (EC2) .. amazon linux.
Also, if I try to run the simple.js directly on linux, it is successfully connecting to my rabbitmq server (which is dockerized).
Please help me out here !!

Related

Can't get a ws WebSocket server to run on Vite dev server. WS_ERR_INVALID_CLOSE_CODE

I'm trying to get a WebSocket server to run on top of Vite's built-in dev server. I'm grabbing the httpServer instance directly from Vite and asking ws to listen on it, and it gives a fatal error which I can't find mentioned anywhere on the web.
I tried manually listening for "upgrade" events on Vite's httpServer and calling ws.Server.handleUpgrade() myself, but that gives me the same exact error. If I run all the code and simply leave off the call to handleUpgrade() then it will stop giving any errors. The error definitely seems to come from handleUpgrade(), I just have no clue what the error means or how to fix it.
It should be noted that I'm using SvelteKit and TypeScript in this project. This is my vite.config.ts file:
import type { UserConfig } from 'vite';
import { sveltekit } from '#sveltejs/kit/vite';
import { WebSocketServer } from "ws";
const config: UserConfig = {
plugins: [
sveltekit(),
{
name: "webSocketServer",
configureServer: (viteDevServer: any) => {
const webSocketServer = new WebSocketServer({
server: viteDevServer.httpServer
});
}
}
]
};
export default config;
This is the error I get when running the npm run dev command:
node:events:491
throw er; // Unhandled 'error' event
^
RangeError: Invalid WebSocket frame: invalid status code 16001
at Receiver.controlMessage (C:\Users\MSJim\Documents\programming-data\visual-studio-code\frontends\sveltekit-websockets-chat\node_modules\ws\lib\receiver.js:566:18)
at Receiver.getData (C:\Users\MSJim\Documents\programming-data\visual-studio-code\frontends\sveltekit-websockets-chat\node_modules\ws\lib\receiver.js:442:42)
at Receiver.startLoop (C:\Users\MSJim\Documents\programming-data\visual-studio-code\frontends\sveltekit-websockets-chat\node_modules\ws\lib\receiver.js:158:22)
at Receiver._write (C:\Users\MSJim\Documents\programming-data\visual-studio-code\frontends\sveltekit-websockets-chat\node_modules\ws\lib\receiver.js:84:10)
at writeOrBuffer (node:internal/streams/writable:392:12)
at _write (node:internal/streams/writable:333:10)
at Writable.write (node:internal/streams/writable:337:10)
at Socket.socketOnData (C:\Users\MSJim\Documents\programming-data\visual-studio-code\frontends\sveltekit-websockets-chat\node_modules\ws\lib\websocket.js:1274:35)
at Socket.emit (node:events:525:35)
at addChunk (node:internal/streams/readable:324:12)
Emitted 'error' event on WebSocket instance at:
at Receiver.receiverOnError (C:\Users\MSJim\Documents\programming-data\visual-studio-code\frontends\sveltekit-websockets-chat\node_modules\ws\lib\websocket.js:1160:13)
at Receiver.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
code: 'WS_ERR_INVALID_CLOSE_CODE',
[Symbol(status-code)]: 1002
}
Where it reads invalid status code 16001, the 16001 seems to change every time I run it. I have gotten 39338, 38329, and 29320 when running it 3 additional times.

Unable to get information using https second time(Error: write EPROTO ... final_renegotiate:unsafe legacy renegotiation disabled)

I developed a server which works fine on my system. Then I got a VPS(Virtual Private Server) from my university to deploy the server there too!
To deploy my server on VPS I used docker but I got a strange result when I ran it! I debug the program and find where problem is but I don't know why it occurs and how to fix it.
I use a remote database to get safe primes. First time I get the information without any problem but when server tries to connect to the database for second time, it gets below error:
node:events:498
throw er; // Unhandled 'error' event
^
Error: write EPROTO 80B9B7E0587F0000:error:0A000152:SSL routines:final_renegotiate:unsafe legacy renegotiation disabled:../deps/openssl/openssl/ssl/statem/extensions.c:907:
at WriteWrap.onWriteComplete [as oncomplete] (node:internal/stream_base_commons:94:16)
Emitted 'error' event on ClientRequest instance at:
at TLSSocket.socketErrorListener (node:_http_client:442:9)
at TLSSocket.emit (node:events:520:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
errno: -71,
code: 'EPROTO',
syscall: 'write'
}
Node.js v17.4.0
npm notice
npm notice New minor version of npm available! 8.3.1 -> 8.5.2
npm notice Changelog: <https://github.com/npm/cli/releases/tag/v8.5.2>
npm notice Run `npm install -g npm#8.5.2` to update!
npm notice
The simplified server I used to test:
const express = require('express');
const debug = require('debug');
const https = require('https')
const log = debug('app::main-Interface');
const args = process.argv.slice(2);
const app = express();
const port = args[0] || process.env.port || 3000;
function sleep(toSleep){
return new Promise((resolve, reject)=>{
setTimeout(() => {
resolve(true)
}, toSleep);
})
}
async function initializeRemotely(lengthOfOrder = 4096){
return new Promise((resolve, reject)=>{
https.get(`https://2ton.com.au/getprimes/random/${lengthOfOrder}`,
(res)=>{
res.on('data', async (data)=>{
log('Data received!')
resolve(true);
})
}
)
})
}
async function DEBUG(){
let breakTime = 5000;
while(true){
await initializeRemotely()
log('First operation succeed')
await sleep(breakTime);
breakTime *= 2;
}
}
app.listen(port, async () => {
log(`Server started listening on port : ${port}`);
//schedulerPool.MSRulesWatcher(config.get('Times.schedulers'));
DEBUG()
});
I run this code on my system using below command line:
$ DEBUG=app::* node server.js
app::main-Interface Server started listening on port : 3000 +0ms
app::main-Interface Data received! +2s
app::main-Interface First operation succeed +4ms
app::main-Interface Data received! +6s
app::main-Interface First operation succeed +1ms
app::main-Interface Data received! +11s
app::main-Interface First operation succeed +2ms
^C
As you can see it works fine!
The docker file I use to deploy the server is as below(./deploy/Dockerfile):
FROM node:alpine
EXPOSE 3000
WORKDIR /interface
COPY package.json .
RUN npm install
COPY . .
And the content of ./docker-compose.yml:
version: "3"
services:
interface:
image: interface
container_name: interface
build:
context: .
dockerfile: ./deploy/Dockerfile
entrypoint: ["npm", "run", "development"]
Then I run the docker image in VPS using below commands:
$ sudo docker-compose build
$ sudo docker-compose up -d
And the log of server is shown below:
$ sudo docker logs [container-name]
> export NODE_ENV=development; export DEBUG=app:*; node server.js
2022-02-25T17:06:37.963Z app::main-Interface Server started listening on port : 3000
2022-02-25T17:06:40.992Z app::main-Interface Data received!
2022-02-25T17:06:40.998Z app::main-Interface First operation succeed
node:events:498
throw er; // Unhandled 'error' event
^
Error: write EPROTO 80B991E6EB7F0000:error:0A000152:SSL routines:final_renegotiate:unsafe legacy renegotiation disabled:../deps/openssl/openssl/ssl/statem/extensions.c:907:
at WriteWrap.onWriteComplete [as oncomplete] (node:internal/stream_base_commons:94:16)
Emitted 'error' event on ClientRequest instance at:
at TLSSocket.socketErrorListener (node:_http_client:442:9)
at TLSSocket.emit (node:events:520:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
errno: -71,
code: 'EPROTO',
syscall: 'write'
}
Node.js v17.4.0
npm notice
npm notice New minor version of npm available! 8.3.1 -> 8.5.2
npm notice Changelog: <https://github.com/npm/cli/releases/tag/v8.5.2>
npm notice Run `npm install -g npm#8.5.2` to update!
npm notice
Which indicates server can connect to the database first time but second time it gets this error.
MY QUESTIONS:
First of all, I'm really curious to find out why this problem occurs?
How can I fix it?
INFORMATION
VPS information:
$ uname -a
Linux vote 5.4.0-26-generic #30-Ubuntu SMP Mon Apr 20 16:58:30 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
My system information:
$ uname -a
Linux milad-pc 5.4.178-1-MANJARO #1 SMP PREEMPT Tue Feb 8 20:03:41 UTC 2022 x86_64 GNU/Linux

Truffle migrate --network bsc error: header not found

When trying to run truffle migrate --network bsc, truffle usually (not always) manages to deploy the migrations contract, then fails with an error: header not found.
Error [ERR_UNHANDLED_ERROR]: Unhandled error. ({ code: -32000, message: 'header not found' })
at new NodeError (node:internal/errors:363:5)
at Web3ProviderEngine.emit (node:events:354:17)
at D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:54:14
at afterRequest (D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:148:21)
at D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:174:21
at D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:232:9
at D:\Contracts\novaria\node_modules\async\internal\once.js:12:16
at replenish (D:\Contracts\novaria\node_modules\async\internal\eachOfLimit.js:61:25)
at D:\Contracts\novaria\node_modules\async\internal\eachOfLimit.js:71:9
at eachLimit (D:\Contracts\novaria\node_modules\async\eachLimit.js:43:36)
at D:\Contracts\novaria\node_modules\async\internal\doLimit.js:9:16
at end (D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:211:5)
at Request._callback (D:\Contracts\novaria\node_modules\web3-provider-engine\subproviders\rpc.js:70:28)
at Request.self.callback (D:\Contracts\novaria\node_modules\request\request.js:185:22)
at Request.emit (node:events:365:28)
at Request.<anonymous> (D:\Contracts\novaria\node_modules\request\request.js:1154:10)
at Request.emit (node:events:365:28)
at IncomingMessage.<anonymous> (D:\Contracts\novaria\node_modules\request\request.js:1076:12)
at Object.onceWrapper (node:events:471:28)
at IncomingMessage.emit (node:events:377:35)
at endReadableNT (node:internal/streams/readable:1312:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
Here's the config for bsc network:
bsc: {
provider: () => { return new HDWalletProvider(mnemonic, `https://bsc-dataseed2.binance.org/`)},
network_id: 56,
confirmations: 10,
timeoutBlocks: 200,
skipDryRun: true,
},
compilers: {
solc: {
version: "0.8.7", // Fetch exact version from solc-bin (default: truffle's version)
// docker: true, // Use "0.5.1" you've installed locally with docker (default: false)
settings: { // See the solidity docs for advice about optimization and evmVersion
optimizer: {
enabled: true,
runs: 200
},
Deploying to testnet and development works without issue. I have in the past deployed to bsc with truffle (been a while though). I've tried changing RPC urls, and messed around with timeout and confirmations (pretty sure that doesn't make a difference for this error). After searching the internet for solutions, the only answer that seems to have worked for people is to change the RPC, but I haven't had any luck with that. Does anyone have any suggestions?
I had the same problem today. Fixed it by using the Websocket endpoint wss://bsc-ws-node.nariox.org:443 from the smart chain docs https://docs.binance.org/smart-chain/developer/rpc.html

Connection time out when mongoose attempts to connect to a mongodb instance running in docker

I am developing a Nodejs application locally in a Windows machine. For that I decided to run Mongodb inside a Docker container simply to learn how to use Docker. I am also running Mongo-express in another container in order to manage the database.
The problem is when I execute the file to connect to the database, a connection time out occours.
This is the file with the Database code:
let mongoose = require('mongoose');
let debug = require('debug')('s-optimizer:mongoDb')
mongoose.connect("mongodb://192.168.99.100:27017/local", {
user: "Lab",
pass: "123123as",
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => debug("Success"))
.catch((error) => debug(error))
let db = mongoose.connection
db.on('error', () => debug("Connection Error"));
db.once('open', () => debug("Connection established"))
And this is the error:
s-optimizer:mongoDb MongooseTimeoutError: Server selection timed out after 30000 ms
s-optimizer:mongoDb at new MongooseTimeoutError (C:\Users\vmari\Projects\S-optimazer\node_modules\mongoose\lib\error\timeout.js:22:11)
s-optimizer:mongoDb at NativeConnection.Connection.openUri (C:\Users\vmari\Projects\S-optimazer\node_modules\mongoose\lib\connection.js:763:19)
s-optimizer:mongoDb at Mongoose.connect (C:\Users\vmari\Projects\S-optimazer\node_modules\mongoose\lib\index.js:332:15)
s-optimizer:mongoDb at Object.<anonymous> (C:\Users\vmari\Projects\S-optimazer\mongo\Database.js:5:10)
s-optimizer:mongoDb at Module._compile (internal/modules/cjs/loader.js:959:30)
s-optimizer:mongoDb at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
s-optimizer:mongoDb at Module.load (internal/modules/cjs/loader.js:815:32)
s-optimizer:mongoDb at Function.Module._load (internal/modules/cjs/loader.js:727:14)
s-optimizer:mongoDb at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
s-optimizer:mongoDb at internal/main/run_main_module.js:17:11 +0ms
s-optimizer:mongoDb Connection Error +7ms
Information about my environment
I am using docker-machine and virtual box to run Docker in Windows.
This is the enviroment for docker-machine when I run: docker-machine env.
$Env:DOCKER_TLS_VERIFY = "1"
$Env:DOCKER_HOST = "tcp://192.168.99.100:2376"
$Env:DOCKER_CERT_PATH = "C:\Users\vmari\.docker\machine\machines\default"
$Env:DOCKER_MACHINE_NAME = "default"
$Env:COMPOSE_CONVERT_WINDOWS_PATHS = "true"
And the Docker containers running when I do: Docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1d9788a4c5da mongo-express "tini -- /docker-ent…" About an hour ago Up About an hour 0.0.0.0:8081->8081/tcp fervent_chebyshev
c7bab68f0725 mongo "docker-entrypoint.s…" About an hour ago Up About an hour 0.0.0.0:27017->27017/tcp bold_noether
I must point out that I ran mongo-express using docker run -it --rm -d -p 8081:8081 --link bold_noether:mongo mongo-express and that I can access it on the browser on: http://192.168.99.100:8081/. But when I try to connect
to the database container through my code I get the timeout.
Dude white list your IP then check
https://github.com/docker-library/mongo/issues/177
Check the thread it can help you

Mongoose failure to connect to Heroku database locally and process.env.MONGOLAB_URI

I am following a book's instructions. I have no trouble connecting to the local database or to MongoLab online in terminal, but can't run my app locally using my Heroku database with: NODE_ENV=production nodemon bin/www
This is my check in my code to use the online database depending on how I start the app:
if (process.env.NODE_ENV === 'production') {
dbURI= process.env.MONGOLAB_URI;
}
I manually input: heroku config:set MONGOLAB_URI=[my uri] as well as used the heroku config:get MONGOLAB_URI and keep getting: Error: failed to connect to [undefined:27017]
Does anybody have any ideas why I can't connect?
~ $ node app.js
/app/node_modules/connect-mongo/node_modules/mongodb/lib/server.js:228
process.nextTick(function() { throw err; })
^
Error
at Error.MongoError (/app/node_modules/connect-mongo/node_modules/mongodb/node_modules/mongodb-core/lib/error.js:13:17)
at Server.destroy (/app/node_modules/connect-mongo/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:629:47)
at Server.close (/app/node_modules/connect-mongo/node_modules/mongodb/lib/server.js:344:17)
at Db.close (/app/node_modules/connect-mongo/node_modules/mongodb/lib/db.js:267:19)
at /app/node_modules/connect-mongo/node_modules/mongodb/lib/db.js:196:12
at null.<anonymous> (/app/node_modules/connect-mongo/node_modules/mongodb/lib/server.js:226:9)
at g (events.js:180:16)
at emit (events.js:98:17)
at null.<anonymous> (/app/node_modules/connect-mongo/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:238:68)
at g (events.js:180:16)
at emit (events.js:98:17)
at null.<anonymous> (/app/node_modules/connect-mongo/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js:77:12)
at g (events.js:180:16)
at emit (events.js:98:17)
at Socket.<anonymous> (/app/node_modules/connect-mongo/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js:118:49)
at Socket.g (events.js:180:16)
~ $
^^ I am seeing the above
My connection:
omeMongodbServer: {
adapter: 'sails-mongo',
url: process.env.MONGOLAB_URI || 'mongodb://localhost/ts',
},

Resources