I have to dockerize a node app which used redis-server. I used docker-compose and official image of redis there.
But, when I run docker compose up, after hitting the API it gives me an error like this
[ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379
docker-redis | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
I used ioredis package, I give REDIS_PORT and REDIS_HOST as the argument of new Redis()
const Redis = require('ioredis');
const { promisify } = require('util');
const publisher = new Redis({
port: process.env.REDIS_PORT,
host: process.env.REDIS_HOST,
});
here REDIS_HOST='redis' and REDIS_PORT=6379
and this is my docker-compose file
version: '3'
services:
app:
container_name: docker-redis
restart: always
build: .
ports:
- '3000:3000'
links:
- redis
# depends_on:
# - redis
redis:
container_name: redis
image: redis:latest
ports:
- '6379:6379'
command: ['redis-server', '--bind', 'redis', '--port', '6379']
Related
I'm trying to connect my app to a db running with a bitnami image of mongo, I have the docker-compose with the following rules:
version: '3.9'
services:
# Database service
mongodb:
image: 'bitnami/mongodb:5.0.8'
container_name: mongodb
restart: on-failure
environment:
- MONGODB_ROOT_USER=${MONGODB_ROOT_USER}
- MONGODB_ROOT_PASSWORD=${MONGODB_ROOT_PASSWORD}
- MONGODB_USERNAME=${MONGODB_USERNAME}
- MONGODB_PASSWORD=${MONGODB_PASSWORD}
- MONGODB_DATABASE=${MONGODB_DATABASE}
ports:
- "27017:27017"
networks:
- honey-net
# Application service
r4i2:
depends_on:
- mongodb
build:
context: ./r4i2_app
env_file:
- .env
container_name: r4i2
ports:
- "${PORT}:${PORT}"
volumes:
- ./r4i2_app/app_srcs/public/:/r4i2/public/
networks:
- honey-net
networks:
honey-net:
driver: bridge
Is in the same net and also have the environment variables for start the db but I get this error:
MongooseServerSelectionError: connect ECONNREFUSED 172.20.0.2:27017
In the other hand I also have the js file to connect to the db:
require('dotenv').config();
const mongoose = require('mongoose')
const clc = require('cli-color');
const connectDB = () => {
const MONGODB_USERNAME=process.env.MONGODB_USERNAME;
const MONGODB_PASSWORD=process.env.MONGODB_PASSWORD;
const MONGODB_DATABASE=process.env.MONGODB_DATABASE;
const dbUri = `mongodb://${MONGODB_USERNAME}:${MONGODB_PASSWORD}#mongodb:27017/${MONGODB_DATABASE}`;
mongoose.connect(dbUri, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log(clc.cyanBright('Debug: Database connected successfully')))
.catch(e => console.log(e));
}
module.exports = { connectDB }
I just wanna connect my app to my db in localhost using docker-compose.
I'm following a tutorial from youtube creating a simple dockerized CRUD application in Express, Node.js, Mongo & Redis. I stucked at video 3:06:57 on Authentication with sessions & Redis.
The initial issue I faced below when I send a POST
ClientClosedError: The client is closed
at Commander._RedisClient_sendCommand (/app/node_modules/#node-redis/client/dist/lib/client/index.js:408:31)
at Commander.commandsExecutor (/app/node_modules/#node-redis/client/dist/lib/client/index.js:166:154)
at Commander.BaseClass.<computed> [as set] (/app/node_modules/#node-redis/client/dist/lib/commander.js:8:29)
at RedisStore.set (/app/node_modules/connect-redis/lib/connect-redis.js:65:21)
at Session.save (/app/node_modules/express-session/session/session.js:72:25)
at Session.save (/app/node_modules/express-session/index.js:406:15)
at ServerResponse.end (/app/node_modules/express-session/index.js:335:21)
at ServerResponse.send (/app/node_modules/express/lib/response.js:221:10)
at ServerResponse.json (/app/node_modules/express/lib/response.js:267:15)
at exports.login (/app/controllers/authController.js:45:28)
[nodemon] app crashed - waiting for file changes before starting...
I found out that the issue above was due to Redis version, the tutorial video was using Redis 3.0+ if not mistaken , but I'm having Redis 6.0+ .So I added the line redisClient.connect().catch(console.error); but second issue happen.
Error: connect ECONNREFUSED 127.0.0.1:6379
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1138:16) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 6379
}
the source files as below:
index.js:
const express = require("express");
const mongoose = require("mongoose");
const session = require("express-session");
const redis = require("redis");
let RedisStore = require("connect-redis")(session);
const { MONGO_PASSWORD, MONGO_IP, MONGO_PORT, MONGO_USER, REDIS_URL, REDIS_PORT, SESSION_SECRET } = require("./config/config");
let redisClient = redis.createClient({
host: REDIS_URL,
port: REDIS_PORT,
})
// let redisClient = createClient({
// host: REDIS_URL,
// port: REDIS_PORT
// });
//redisClient.connect().catch(console.error);
redisClient.on('error', err => {console.log('Error ' + err);});
docker-compose.yml:
version : "3"
services :
node-app:
build : .
ports:
- "3000:3000"
environment:
- PORT=3000
depends_on:
- mongo
mongo:
image: mongo
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=password
volumes:
- mongo-db:/data/db
redis:
image: redis
volumes:
mongo-db:
docker-compose.dev.yml:
version : "3"
services :
node-app:
build:
context: .
args:
NODE_ENV: development
volumes:
- ./:/app
- /app/node_modules
environment:
- NODE_ENV=development
- MONGO_USER=admin
- MONGO_PASSWORD=password
- SESSION_SECRET=secret
command: npm run dev
mongo:
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=password
config.js:
module.exports = {
MONGO_IP: process.env.MONGO_IP || "mongo",
MONGO_PORT: process.env.MONGO_PORT || 27017,
MONGO_USER: process.env.MONGO_USER,
MONGO_PASSWORD: process.env.MONGO_PASSWORD,
REDIS_URL: process.env.REDIS_URL || "redis",
REDIS_PORT: process.env.REDIS_PORT || 6379,
SESSION_SECRET: process.env.SESSION_SECRET
}
I did a check to the redis container logs and it's up and running. Also it should be in the same network with the node-app.
docker command : docker-compose -f docker-compose.yml -f docker-compose.dev.yml up -d
Full source code from tutor https://github.com/Sanjeev-Thiyagarajan/node-docker
Redis client doesn't work in v4 of Redis. Replace the redisClient code with this:
let redisClient = redis.createClient({
legacyMode: true,
socket: {
port: REDIS_PORT,
host: REDIS_URL
}
})
redisClient.connect().catch(console.error)
I've tried this code and it solves the problem at 100%.
let redisClient = redis.createClient({
legacyMode: true,
socket: {
port: REDIS_PORT,
host: REDIS_URL
}
});
redisClient.connect().catch(console.error)
Here we are with another docker issue. I am writing a node app that needs to use redis, node app is inside a container and redis another container both on the same custom network.
Using docker compose:
node-app-test:
platform: linux/amd64
container_name: node-app-test
depends_on:
- redis-test
image: my-custom-image
ports:
- 8000:8000
networks:
- my-network-test
links:
- redis-test
redis-test:
platform: linux/amd64
container_name: redis-test
image: redis
ports:
- 6379:6379
networks:
- my-network-test
The basics of the node app that connects to redis is simply:
const redis = require("redis");
const redisClient = redis.createClient({
host: 'redis-test',
port: 6379
})
redisClient.connect();
redisClient.on("connect", () => {
console.log("REDIS IS CONNECTED")
})
redisClient.on("error", (error) => {
console.log("REDIS ERROR", error)
})
The error event is trapped with the following:
connect ECONNREFUSED 127.0.0.1:6379
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1195:16) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 6379
}
I have done a test outside of the container and the redis container does accept connections, not sure what's going on.
UPDATE
I think it's the redis node library that's the issue, it works if i connect by URL instead of host and port
I have a NodeJS Application that connects to a MongoDB server.
Both the node application and MongoDB server are served in a docker container (with docker-compose)
docker-compose.yml:
version: '3'
services:
redis:
image: "redis:alpine"
ports:
- "6379:6379"
expose:
- 6379
restart:
always
container_name: redis-server
mongo:
image: "mongo"
command: mongod --bind_ip_all --replSet rs8
volumes:
- c:\mongo\data:/data/db
ports:
- "27017:27017"
expose:
- 27017
restart:
always
container_name: mongo-server
accounts-service:
depends_on:
- redis
- mongo
build:
context: .
dockerfile: GenericNodeJSDockerfile
container_name: accounts-service
ports:
- "8001:8001"
In the node app, the connection in mongo looks like this:
const m = require('mongoose')
const connectionConfig = {
useUnifiedTopology: true,
useNewUrlParser: true,
};
let connectionString = 'mongodb://mongo:27017/mydb/replicaSet=rs8';
m.connect(connectionString , connectionConfig).then(_ => {
console.log("Connected to MongoDB")
}).catch(err => {
console.log("Failed connecting to MongoDB: " + err);
});
And the error that is thrown is:
Failed connecting to MongoDB: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
But when I'm commenting the row contains useUnifiedTopology option, the connection succeeds.
Does anyone have an idea how to fix it?
It turns out that I had a wrong hosts file configuration that made this issue.
I have a node app which connects to NATS server. Below is my docker-compose.yml for both the servers.
version: "3"
services:
app:
image: node:12.13.1
volumes:
- ./:/app
working_dir: /app
depends_on:
- mongo
- nats
environment:
NODE_ENV: development
ports:
- 3000:3000
command: npm run dev
mongo:
image: mongo
expose:
- 27017
volumes:
- ./data/db:/data/db
nats:
image: 'nats:2.1.2'
# entrypoint: "/gnatsd -DV"
# entrypoint: "/nats-server -p 4222 -m 8888 "
expose:
- "4222"
ports:
- "8222:8222"
hostname: nats-server
app.post('/pets', function(req, res, next) {
let nats = NATS.connect('nats://nats-server:4222');
nats.publish('foo', 'Hello World!');
res.json({ stats: 'success' });
});
The above nodejs snippet gives me:
NatsError: Could not connect to server: Error: getaddrinfo ENOTFOUND nats-server
If I use let nats = NATS.connect() it gives me:
NatsError: Could not connect to server: Error: connect ECONNREFUSED 127.0.0.1:4222
Kindly throw me some ideas on how to resolve this issue.
Thanks.
let nats = NATS.connect('nats://nats:8222');
you need to use the name of the container, and attach the internal port