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

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.

Related

Can't access Adonis from Docker Container

I use Docker to contain my Adonis app. The build was success but when I access the app, I got ERR_SOCKET_NOT_CONNECTED or ERR_CONNECTION_RESET.
My docker compose contains adonis and database. Previously, I use the setup similar with this for my expressjs app, and it has no problem.
The adonis .env is remain standard, modification.
This is my setup:
# docker-compose.yml
version: '3'
services:
adonis:
build: ./adonis
volumes:
- ./adonis/app:/usr/src/app
networks:
- backend
links:
- database
ports:
- "3333:3333"
database:
image: mysql:5.7
ports:
- 33060:3306
networks:
- backend
environment:
MYSQL_USER: "user"
MYSQL_PASSWORD: "root"
MYSQL_ROOT_PASSWORD: "root"
networks:
backend:
driver: bridge
# adonis/Dockerfile
FROM node:12-alpine
RUN npm i -g #adonisjs/cli
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY ./app/. .
RUN npm install
EXPOSE 3333
CMD ["adonis", "serve", "--dev"]
I couldn't spot anything wrong with my setup.
The serve command starts the HTTP server on the port defined inside the .env file in the project root.
You should have something like this(note that HOST has to be set to 0.0.0.0 instead of localhost to accept connections from the outside):
HOST=0.0.0.0
PORT=3333
APP_URL=http://${HOST}:${PORT}

Redis connection failed

I'm building an application which uses Node, redis and mongo. I finished the development, and I want to containerize it with docker.
Here's my Dockerfile:
FROM node:13.8.0-alpine3.11
RUN npm install -g pm2
WORKDIR /user/src/app
COPY package*.json ./
RUN npm install --production
COPY . .
EXPOSE 3000
And here my docker-compose.yml
version: '3'
services:
redis-server:
container_name: scrapr-redis
image: 'redis:6.0-rc1-alpine'
ports:
- '6379:6379'
mongo-db:
container_name: scrapr-mongo
image: mongo
ports:
- '27017:27017'
command: --auth
environment:
- MONGO_INITDB_ROOT_USERNAME=user
- MONGO_INITDB_ROOT_PASSWORD=pass
- MONGO_INITDB_DATABASE=db
app:
container_name: scrapr-node
restart: always
build: .
ports:
- '3000:3000'
- '3001:3001'
links:
- mongo-db
depends_on:
- redis-server
environment:
- DB_USER=user
- DB_PWD=pass
- DB_NAME=db
- REDIS_HOST=redis-server
command: 'node index.mjs'
I can start the service successfully, but when node starts, it generates the following error:
Error Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
When I do docker ps -a, I can see that all containers are running:
Why can't it connect with redis? What did I miss?
127.0.0.1 does not look right to me at all. Let me get the quick checks out of the way first, are you sure you are using the REDIS_HOST env variable in the node app correctly? I would add some console logging to your node app to echo out the env variables to check what they are.
Secondly try attach to the running scrapr-node with docker container exec -it scrapr-node sh or /bin/bash if sh does not work.
Then run nslookup scrapr-redis from the shell, this will give you the ip address of the redis container. if ping scraper-redis returns then you know its an issue with your node app not the docker network.
you can also exec into the redis node and run hostname -I which should show the same ip address as you saw from the other container.
This should help you to debug the issue.
EDIT:
Ensure that you are correctly getting the value from your environment into your node app using process.env.REDIS_HOST and then correctly using that value when connecting to redis something like:
const redisClient = redis.createClient({
host: process.env.REDIS_HOST,
port: 6379
});
I would not try and force 127.0.0.1 on the docker network (if that is even possible) it is reserved as the loopback address.

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

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')
}
);

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