how to connect to an mqtt broker on ec2 via mqtt.js? - javascript

I want: to push a message from a raspberrypi via node package mqtt.js to/through a ec2 mosquitto broker and back to the raspberrypi.
I've installed a mosquitto broker on my ec2 instance. using these commands:
ssh -i awskeypair.pem ubuntu#ec2-54-153-18-31.us-west-1.compute.amazonaws.com
sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
sudo apt-get update
sudo apt-get install mosquitto
sudo apt-get install mosquitto-clients
mosquitto
and on a raspberrypi I've installed mqtt.js via node.
installed package:
npm install mqtt --save
index.js
var mqtt = require('mqtt');
// pretty sure this var client line isn't connecting if I use test.mosquitto.org it works just fine
var client = mqtt.connect('mqtt://ec2-54-153-18-31.us-west-1.compute.amazonaws.com');
client.subscribe('presence');
client.publish('presence', 'Hello mqtt');
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString());
});
client.end();
Problem: I'm pretty sure my ec2 instance with the mosquitto broker isn't accessible
QUESTION:
How do I connect to my ec2 broker?
notes on my broker
ubuntu#ip-172-31-6-23:~$ mosquitto
1425504937: mosquitto version 1.4 (build date 2015-02-18 21:33:29+0000) starting
1425504937: Using default config.
1425504937: Opening ipv4 listen socket on port 1883.

Sounds like you didn't open the port 1883 in your security group. If the security group is not the problem, double check that you don't have IPTables running on your EC2 instance

Not sure if this relates to ec2 as well, but for IoT I got MQTT.js working by setting up the options object correctly in the connect call.
var client = mqtt.connect('mqtts://<yourawsid>.iot.us-east-1.amazonaws.com', {
port: '8883',
cert: fs.readFileSync('<path>/cert.pem'),
key: fs.readFileSync('<path>/privateKey.pem')
}
);

Related

In VPS with OS Ubuntu 18.04 "apt install nginx" shows libc6 & libcrypt1 error. So, how to install libc6 & libcrypt1 in it?

I am trying to host node app on vps using nginx server. But I am unable to install nginx in ubuntu 18.04 version after apt install nginx shows:
The following packages have unmet dependencies:
nginx : Depends: libc6 (>= 2.28) but 2.27-3ubuntu1.6 is to be installed
Depends: libcrypt1 (>= 1:4.1.0) but it is not installable
E: Unable to correct problems, you have held broken packages.
Anyone face such problem & how do you solve it? I also got problem in nginx.cnf, after nginx -t to check it shows brotil error.
ubuntu nginx installation
node app
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
I want to host node app to serve backend API's. So, I bought VPS from Hostinger website & have installed Ubuntu v18.04 in it. Then I successfully installed nodejs to run nodeapp & pm2 to manage processes. It was successfully running on port 8000. But problem is when I called the API from frontend, shows SSL security error.
So, for that I tried to install nginx but shows error & I guess for SSL nginx server is required. Now I am stuck in nginx installation.
I need some solution from someone who also face same problem.
You should consider upgrading to more recent versions of ubuntu as version 18.04 will reach EOL on April 30, 2023
Otherwise, you may try upgrading packages on your system, as it currently has libc6 version 2.27 while version 2.28 or higher is required.
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install nginx
if you continue seeing an issue, you may try
sudo apt-get install --no-install-recommends nginx
Actually, I had installed Ubuntu v18.04 with plex control panel. I guess that is giving me the issue.
Now I installed Ubuntu v18.04 only. It is working fine now. I successfully installed nginx and it is running properly.

redis.createClient() doesn't work in docker [duplicate]

I'm trying to allow communication between my nodeJs docker image with my redis docker image (Mac OS X environment):
nodeJs Dockerfile:
FROM node:4.7.0-slim
EXPOSE 8100
COPY . /nodeExpressDB
CMD ["node", "nodeExpressDB/bin/www"]
redis Dockerfile:
FROM ubuntu:14.04.3
EXPOSE 6379
RUN apt-get update && apt-get install -y redis-server
nodeJs code which is trying to connect to redis is:
var redis = require('redis');
var client = redis.createClient();
docker build steps:
docker build -t redis-docker .
docker build -t node-docker .
docker run images steps flow:
docker run -p 6379:6379 redis-docker
docker run -p 8100:8100 node-docker
ERROR:
Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
at Object.exports._errnoException (util.js:907:11)
at exports._exceptionWithHostPort (util.js:930:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1078:14)
What should I do inorder to connect to Redis from node-docker?
Redis runs in a seperate container which has seperate virtual ethernet adapter and IP address to the container your node application is running in. You need to link the two containers or create a user defined network for them
docker network create redis
docker run -d --net "redis" --name redis redis
docker run -d -p 8100:8100 --net "redis" --name node redis-node
Then specify the host redis when connecting in node so the redis client attempts to connect to the redis container rather than the default of localhost
const redis = require('redis')
const client = redis.createClient(6379, 'redis')
client.on('connect', () => console.log('Connected to Redis') )
Docker Compose can help with the definition of multi container setups.
version: '2'
services:
node:
build: .
ports:
- "8100:8100"
networks:
- redis
redis:
image: redis
networks:
- redis
networks:
redis:
driver: bridge
Solution
const client = redis.createClient({
host: 'redis-server',
port: 6379
})
Then rebuild ur docker with => docker-compose up --build
When connecting in node, use redis-docker in the function argument you pass the server IP.
If you can create a new redis docker instance, try mapping the container port to host:
docker run --name some-redis -p 6379:6379 -d redis
docker container start some-redis
Now, you can start the container and connect with host 127.0.0.1
const redis = require("redis");
const client = redis.createClient({
host: '127.0.0.1',
port: '6379'
});
if redis installed then run command
sudo apt-get install redis-server
Then you will get your site running.
You can also change your /etc/hosts file to update the dockerip of the redis container.
Find the docker ip by using docker inspect
Download the redis server.
run the redis server.
and then run your project.
It should work just fine. Here's the download link:
Github - Redis Download Packages
I hope it works.

node.js script works off command line but not from browser?

I launched and amazon ec2 instance running ubuntu 12.04
I then followed the instructions to install node.js from here http://howtonode.org/how-to-install-nodejs
sudo apt-get install g++ curl libssl-dev apache2-utils
sudo apt-get install git-core
git clone git://github.com/ry/node.git
cd node
./configure
make
sudo make install
I then used the example code to make hello.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Node.js\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
I then ran hello.js
/var/www$ node hello.js
Server running at http://127.0.0.1:8124/
However, when I try to access this from the url, with http://ec2-***.compute-1.amazonaws.com:8124/ I get an error page from my browser.
Any advice on how to get it to show up in the browser?
EDIT
I'm still encountering this problem after changing the above line of code
}).listen(8124, "127.0.0.1");
to this
}).listen(8124);
127.0.0.1 is the loopback address. Only the host can access it. If you want to listen on any available IP, just don't specify that parameter. Otherwise, specify the real IP you want to listen on.
I also had same issue, Uninstalling skype worked for me, You can also search for some setting which force skype to move to some other port.

Installing and running browserquest on ubuntu

I have installed node.js and necessary packages to run browserquest. I have started the browserquest server, which is running on port 8080 and when I go to my browser and type http://localhost:8080/status I can see that server is running and currently no clients are connected. I build the client with configurations like this in client/config/build_config.json file
{
"host": "http://127.0.0.1",
"port": 8080
}
I build my client within bin/build.sh. Then I run this command to create http-server to serve client files.
http-server path-to-client-build -p 8000
I can see the index page with the httpserver running by going to http://localhost:8000/index.html but when I try to connect it gets stuck after saying connecting to server.
NOTE: I am using this http-server to host client files http://search.npmjs.org/#/http-server
I think the client-build has some problems on the current release on github. Instead I have used the actual client folder. I have followed these steps to make it work.
Make sure you have installed node and npm.
1) get a copy from github repo.
git clone https://github.com/mozilla/BrowserQuest.git
2) Install the required node packages for the server
npm install underscore log bison websocket websocket-server sanitizer memcache
3) Start the server
node server/js/main.js
4) go to the client directory and install http-server module to serve the client files
cd client
npm install -g http-server
5) edit config_build.json-dist to point to your host ip and port (in my case 127.0.0.1 localhost)
{
"host": "127.0.0.1",
"port": 8000,
"dispatcher": false
}
6) copy the edited config_build.json-dist to 2 new files
cp config_build.json-dist config_build.json
cp config_build.json-dist config_local.json
7) copy shared folder into client folder
cp -r ../shared .
8) start the http-server to serve the client files
http-server
And your server and client should be running. You can check if the server is running by going to http://ipaddress:port/status which should display an array of connected clients. If none an empty array. And your client should be running on http://ipaddress:8000/index.html
based on the tutorial from dirkk0
https://gist.github.com/2275361

Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED

I working with node.js by expressjs I try to store an account to session. So, i try to test to use session with code in expressjs
var RedisStore = require('connect-redis')(express);
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));
but I got error Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED. Please help me resolve this problem
After you install redis, type from terminal:
redis-server
and you'll have redis running
I solve this problem in next way:
sudo apt-get install redis-server
then run command to confirm that everything ok:
sudo service redis-server status
And the output will be: redis-server is running - that means that the problem is solved.
Install redis on your system first -
brew install redis
then start the redis server -
redis-server
I'm on windows, and had to install Redis from here and then run redis-server.exe.
From the top of this SO question.
For those of you who are using docker with docker-compose and Typescript my solution was
import { RedisClient } from 'redis';
const pubClient = new RedisClient({ url: 'redis://redis:6379' });
to
import { createClient } from 'redis';
const pubClient = createClient({ url: 'redis://redis:6379' });
docker-compose.yml
version: '3.9'
services:
main:
build:
context: .
target: development
ports:
- ${PORT}:${PORT}
volumes:
- ./src:/usr/src/app/src
- /app/node_modules
env_file:
- .env
command: npm run start:dev
depends_on:
- mongo
- redis
mongo:
image: mongo:5.0.2-focal
volumes:
- mongo-data:/data/db
mongo-express:
image: mongo-express:0.54.0
ports:
- 8081:8081
depends_on:
- mongo
redis:
image: redis:6.2.5-alpine
volumes:
mongo-data:
Simple solution:
only hit below commend once and restart your server again
redis-server
Using Windows 10?
Go here: https://learn.microsoft.com/en-us/windows/wsl/wsl2-install
Then run...
$ wget https://github.com/antirez/redis/archive/5.0.5.tar.gz <- change this to whatever Redis version you want (https://github.com/antirez/redis/releases)
$ tar xzf redis-5.0.5.tar.gz
$ cd redis-5.0.5
$ make
for Windows users, you can use chocolatey to install Redis
choco install redis-64
then run server from
C:\ProgramData\chocolatey\lib\redis-64\redis-server.exe
I also have the same problem, first I tried to restart redis-server by sudo service restart but the problem still remained. Then I removed redis-server by sudo apt-get purge redis-server and install it again by sudo apt-get install redis-server and then the redis was working again. It also worth to have a look at redis log which located in here /var/log/redis/redis-server.log
I used ubuntu 12.04
I solved that problem by installing redis-server
redis-server installation for ubuntu 12.04
some configuration will new root permission
Also listed manuals for other OS
Thanks
For me I had this issue on Ubuntu 18.x, but my problem was that my redis-server was running on 127.0.0.1 but I found out I needed to run it on my IP address xxx.xx.xx.xx
I went into my Ubuntu machine and did the following.
cd /etc/redis/
sudo vim redis.conf
Then I edited this part.
################################## NETWORK #####################################
# By default, if no "bind" configuration directive is specified, Redis listens
# for connections from all the network interfaces available on the server.
# It is possible to listen to just one or multiple selected interfaces using
# the "bind" configuration directive, followed by one or more IP addresses.
#
# Examples:
#
# bind 192.168.1.100 10.0.0.1
# bind 127.0.0.1 ::1
#
# ~~~ WARNING ~~~ If the computer running Redis is directly exposed to the
# internet, binding to all the interfaces is dangerous and will expose the
# instance to everybody on the internet. So by default we uncomment the
# following bind directive, that will force Redis to listen only into
# the IPv4 loopback interface address (this means Redis will be able to
# accept connections only from clients running into the same computer it
# is running).le to listen to just one or multiple selected interfaces using
#
# IF YOU ARE SURE YOU WANT YOUR INSTANCE TO LISTEN TO ALL THE INTERFACES
# JUST COMMENT THE FOLLOWING LINE.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# bind 127.0.0.1 ::1 10.0.0.1
bind 127.0.0.1 ::1 # <<-------- change this to what your iP address is something like (bind 192.168.2.2)
Save that, and then restart redis-server.
sudo service redis-server restart or simply run redis-server
For windows platform, You must check if redis-server is running on given ip:port. you can find redis configuration at installation directory /conf/redis.conf. by default client accept 127.0.0.1:6379.
I'm on MBP , and install redis detail my problem was resolved .Fixed the
Download, extract and compile Redis with:
$ wget http://download.redis.io/releases/redis-3.0.2.tar.gz
$ tar xzf redis-3.0.2.tar.gz
$ cd redis-3.0.2
$ make
The binaries that are now compiled are available in the src directory.
Run Redis with:
$ src/redis-server
I think maybe you installed redis by source code.If that you need locate to redis-source-code-path/utils and run sudo install_server.sh command.
After that, make sure redis-server has been running as a service for your system
sudo service redis-server status
PS: based on Debian/Ubuntu
In case of ubuntu, the error is due to redis-server not being set up.
Install the redis-server again and then check for the status.
If there is no error, then a message like this would be displayed :-
● redis-server.service - Advanced key-value store
Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2018-01-17 20:07:27 IST; 16s ago
Docs: http://redis.io/documentation,
man:redis-server(1)
Main PID: 4327 (redis-server)
CGroup: /system.slice/redis-server.service
└─4327 /usr/bin/redis-server 127.0.0.1:6379
You have to install redis server first;
You can install redis server on mac by following step -
$ curl -O http://download.redis.io/redis-stable.tar.gz
$ tar xzvf redis-stable.tar.gz
$ cd redis-stable
$ make
$ make test
$ sudo make install
$ redis-server
Good luck.
Your connection to redis is failing. Try restarting your redis server, then starting up your client again by running these 3 commands:
sudo service redis-server restart
redis-server
redis-cli
For Windows I solved this by...
using...
let redisClient = createClient({
legacyMode: true ,
url: 'redis://redis:6379',
});
Its for redis version > 4.0
You can refer to the image below.
Try upgrading your node to latest version.
sudo npm cache clean -f
sudo npm install -g n
sudo n stable
version 0.4 may not work properly.

Categories

Resources