Connection time out when mongoose attempts to connect to a mongodb instance running in docker - node.js

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

Related

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

Docker swarm secret not working correctly in node.js api (mongoDB)

I am trying to get my mongo_username and mongo_password in a swarm secret, but for some reason they are converted? I get this error in the container log
/usr/src/app/node_modules/saslprep/index.js:99
throw new Error(
^
Error: Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3
at saslprep (/usr/src/app/node_modules/saslprep/index.js:99:11)
at continueScramConversation (/usr/src/app/node_modules/mongodb/lib/core/auth/scram.js:126:36)
at /usr/src/app/node_modules/mongodb/lib/core/auth/scram.js:111:5
at MessageStream.messageHandler (/usr/src/app/node_modules/mongodb/lib/cmap/connection.js:277:5)
at MessageStream.emit (events.js:315:20)
at processIncomingData (/usr/src/app/node_modules/mongodb/lib/cmap/message_stream.js:144:12)
at MessageStream._write (/usr/src/app/node_modules/mongodb/lib/cmap/message_stream.js:42:5)
at writeOrBuffer (_stream_writable.js:353:12)
at MessageStream.Writable.write (_stream_writable.js:303:12)
at Socket.ondata (_stream_readable.js:713:22)
at Socket.emit (events.js:315:20)
at addChunk (_stream_readable.js:302:12)
at readableAddChunk (_stream_readable.js:278:9)
at Socket.Readable.push (_stream_readable.js:217:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23)
I added the secret like this
echo admin | docker secret create mongo_username -
echo totallySecurePassword23456789 | docker secret create mongo_password -
and when i log those two secrets in my DB connect function like this:
const mongoose = require("mongoose"); // For connection to DB
const {
MONGO_USERNAME,
MONGO_PASSWORD,
MONGO_HOSTNAME,
MONGO_PORT,
MONGO_DATABASE_NAME,
} = process.env;
console.log(MONGO_USERNAME);
console.log(MONGO_PASSWORD);
console.log(MONGO_HOSTNAME);
console.log(MONGO_PORT);
console.log(MONGO_DATABASE_NAME);
const url = `mongodb://${MONGO_USERNAME}:${MONGO_PASSWORD}#${MONGO_HOSTNAME}:${MONGO_PORT}/${MONGO_DATABASE_NAME}?retryWrites=true$w=majority`;
console.log(url);
const connectDB = async () => {
const conn = await mongoose.connect(url, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
});
console.log(`MongoDB Connected: ${conn.connection.host}`.cyan.underline.bold);
};
module.exports = connectDB;
They show up correctly as:
admin
totallySecurePassword23456789
host.docker.internal
27020
mainDB
and yet the url which is made which is supposed to look like mongodb://admin:totallySecurePassword23456789#host.docker.internal:27020/mainDB?retryWrites=true$w=majority
shows up as #host.docker.internal:27020/mainDB?retryWrites=true$w=majority
And this ofcourse makes the connection fail
the hostname, port and database_name work fine because these are defined as normal environment variables
Any help would be really appreciated, and if more info is needed please let me know!
Edit 1:
Here is the docker-compose file i use to run docker stack:
version: "3.8"
services:
main:
image: main:5.0.0
environment:
- MONGO_USERNAME_FILE=/run/secrets/mongo_username
- MONGO_PASSWORD_FILE=/run/secrets/mongo_password
- MONGO_HOSTNAME=host.docker.internal
- MONGO_PORT=27020
- MONGO_DATABASE_NAME=mainDB
secrets:
- mongo_username
- mongo_password
networks:
- main-net
ports:
- "80:3001"
deploy:
replicas: 1
restart_policy:
condition: on-failure
delay: 10s
window: 60s
networks:
main-net:
driver: overlay
secrets:
mongo_username:
external: true
mongo_password:
external: true
Edit 2:
Fixed the compose file missing the _FILE behind the username and password
After lots of investigating i found out i was having this problem https://github.com/aspnet/Configuration/issues/701, with no good fix found i settled on editing the entrypoint i was using (https://github.com/BretFisher/node-docker-good-defaults/blob/main/docker-entrypoint.sh) so it removed the end of line stuff before setting it as a environment variable by using
export "$var"="${val//[$'\t\r\n ']}"
I assume you use gnu bash. If you use echo shell builtin without -n option, it automatically adds new line to provided string.
Try these:
echo -n admin | docker secret create mongo_username -
echo -n totallySecurePassword23456789 | docker secret create mongo_password -
If you want to check your secret value whether includes new line, execute the following command on the machine where your docker cli resides:
docker container exec <your_container_name or id> cat -e /run/secrets/<your_secret_name>
If this command returns your value followed by $ symbol then we can conclude that new line character was appended while you were creating secret.
Note: I presume your container is a linux container. Also, be sure your container is in running state and its PATH environment variable must include the directory path where cat binary reside.

Oracle DB connection with Node.js Getting "Error: Schema User name is not Set! Try Set Environment Variable NODE_ORACLEDB_USER."

I have installed Node JS version 12, cloned node-oracle db from github.
I have also set OCI_LIB_DIR Path as mentioned in this article.
module.exports = {
user : process.env.NODE_ORACLEDB_USER || "hr",
// Get the password from the environment variable
// NODE_ORACLEDB_PASSWORD. The password could also be a hard coded
// string (not recommended), or it could be prompted for.
// Alternatively use External Authentication so that no password is
// needed.
password : process.env.NODE_ORACLEDB_PASSWORD || abcd,
// For information on connection strings see:
// https://oracle.github.io/node-oracledb/doc/api.html#connectionstrings
connectString : process.env.NODE_ORACLEDB_CONNECTIONSTRING || "jdbc:oracle:thin:#localhost:1521/orcl",
// Setting externalAuth is optional. It defaults to false. See:
// https://oracle.github.io/node-oracledb/doc/api.html#extauth
externalAuth : process.env.NODE_ORACLEDB_EXTERNALAUTH ? true : false
};
I have created a basic connection in SQL developer, would it help.
I have installed npm in node-oracledb and also set the username, but when I try to run the command "npm test" , It gives me the error
Deeksha ~/Desktop/nodewithoracle/node-oracledb (master)
$ npm test
> oracledb#4.1.0 test C:\Users\Deeksha\Desktop\nodewithoracle\node-oracledb
> mocha --opts test/opts/mocha.opts
C:\Users\Deeksha\Desktop\nodewithoracle\node-oracledb\node_modules\yargs\yargs.js:1163
else throw err
^
Error: Schema User name is not Set! Try Set Environment Variable NODE_ORACLEDB_USER.
at Object.<anonymous> (C:\Users\Deeksha\Desktop\nodewithoracle\node-oracledb\test\dbconfig.js:48:9)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (C:\Users\850044533\Desktop\nodewithoracle\node-oracledb\test\notes.js:32:18)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at C:\Users\Deeksha\Desktop\nodewithoracle\node-oracledb\node_modules\mocha\lib\mocha.js:330:36
at Array.forEach (<anonymous>)
at Mocha.loadFiles (C:\Users\Deeksha\Desktop\nodewithoracle\node-oracledb\node_modules\mocha\lib\mocha.js:327:14)
at Mocha.run (C:\Users\Deeksha\Desktop\nodewithoracle\node-oracledb\node_modules\mocha\lib\mocha.js:804:10)
at Object.exports.singleRun (C:\Users\Deeksha\Desktop\nodewithoracle\node-oracledb\node_modules\mocha\lib\cli\run-helpers.js:207:16)
at exports.runMocha (C:\Users\Deeksha\Desktop\nodewithoracle\node-oracledb\node_modules\mocha\lib\cli\run-helpers.js:300:13)
at Object.exports.handler (C:\Users\Deeksha\Desktop\nodewithoracle\node-oracledb\node_modules\mocha\lib\cli\run.js:296:3)
at Object.runCommand (C:\Users\Deeksha\Desktop\nodewithoracle\node-oracledb\node_modules\yargs\lib\command.js:242:26)
at Object.parseArgs [as _parseArgs] (C:\Users\Deeksha\Desktop\nodewithoracle\node-oracledb\node_modules\yargs\yargs.js:1087:28)
at Object.parse (C:\Users\Deeksha\Desktop\nodewithoracle\node-oracledb\node_modules\yargs\yargs.js:566:25)
at Object.exports.main (C:\Users\Deeksha\Desktop\nodewithoracle\node-oracledb\node_modules\mocha\lib\cli\cli.js:63:6)
at Object.<anonymous> (C:\Users\Deeksha\Desktop\nodewithoracle\node-oracledb\node_modules\mocha\bin\_mocha:10:23)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
at internal/main/run_main_module.js:17:11
npm ERR! Test failed. See above for more details.
set the credential environment variables to your DB credential values before you start Node.js. The error message says NODE_ORACLEDB_USER is not set.
Alternatively you can set the values directly in your getConnection() calls:
connection = await oracledb.getConnection({ user: 'hr', password: 'welcome', connectString: 'localhost/orcl' });
But be careful of hard coding passwords.
Use a valid connection string; a JDBC connection string is not usable (Node.js is not JDBC). See the node-oracledb doc JDBC and Oracle SQL Developer Connection Strings for how to determine what to use. Based on what you posted, you should use just localhost:1521/orcl.
Save yourself some time, and read the node-oracledb installation manual, the documentation, and the examples.

Docker - SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306

I'm trying to get my nodejs application up and running using a docker container. I have no clue what might be wrong. The credentials seems to be passed correctly when I debug the credentials with the console. Also firing up sequel pro and connecting directly with the same username and password seems to work. When node starts in the container I get the error message:
SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306
The application itself is loading correctly on port 3000, however no data is retrieved from the database. If have also tried adding the environment variables directly to the docker compose file, but this also doesn't seem to work.
My project code is hosted over here: https://github.com/pietheinstrengholt/rssmonster
The following database.js configuration is used. When I add console.log(config) the correct credentials from the .env file are displayed.
require('dotenv').load();
const Sequelize = require('sequelize');
const fs = require('fs');
const path = require('path');
const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname + '/../config/config.js'))[env];
if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}
module.exports = sequelize;
When I do a console.log(config) inside the database.js I get the following output:
{
username: 'rssmonster',
password: 'password',
database: 'rssmonster',
host: 'localhost',
dialect: 'mysql'
}
Following .env:
DB_HOSTNAME=localhost
DB_PORT=3306
DB_DATABASE=rssmonster
DB_USERNAME=rssmonster
DB_PASSWORD=password
And the following docker-compose.yml:
version: '2.3'
services:
app:
depends_on:
mysql:
condition: service_healthy
build:
context: ./
dockerfile: app.dockerfile
image: rssmonster/app
ports:
- 3000:3000
environment:
NODE_ENV: development
PORT: 3000
DB_USERNAME: rssmonster
DB_PASSWORD: password
DB_DATABASE: rssmonster
DB_HOSTNAME: localhost
working_dir: /usr/local/rssmonster/server
env_file:
- ./server/.env
links:
- mysql:mysql
mysql:
container_name: mysqldb
image: mysql:5.7
command: --default-authentication-plugin=mysql_native_password
environment:
MYSQL_RANDOM_ROOT_PASSWORD: "yes"
MYSQL_DATABASE: "rssmonster"
MYSQL_USER: "rssmonster"
MYSQL_PASSWORD: "password"
ports:
- "3307:3306"
volumes:
- /var/lib/mysql
restart: unless-stopped
healthcheck:
test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost"]
timeout: 5s
retries: 10
volumes:
dbdata:
Error output:
{ SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306
app_1 | at Promise.tap.then.catch.err (/usr/local/rssmonster/server/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:128:19)
app_1 | From previous event:
app_1 | at ConnectionManager.connect (/usr/local/rssmonster/server/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:125:13)
app_1 | at sequelize.runHooks.then (/usr/local/rssmonster/server/node_modules/sequelize/lib/dialects/abstract/connection-manager.js:306:50)
app_1 | From previous event:
app_1 | at ConnectionManager._connect (/usr/local/rssmonster/server/node_modules/sequelize/lib/dialects/abstract/connection-manager.js:306:8)
app_1 | at ConnectionManager.getConnection (/usr/local/rssmonster/server/node_modules/sequelize/lib/dialects/abstract/connection-manager.js:247:46)
app_1 | at Promise.try (/usr/local/rssmonster/server/node_modules/sequelize/lib/sequelize.js:564:34)
app_1 | From previous event:
app_1 | at Promise.resolve.retryParameters (/usr/local/rssmonster/server/node_modules/sequelize/lib/sequelize.js:464:64)
app_1 | at /usr/local/rssmonster/server/node_modules/retry-as-promised/index.js:60:21
app_1 | at new Promise (<anonymous>)
Insteaf of localhost point to mysql which is the service name (DNS) that nodejs will resolve into the MySQL container:
DB_HOSTNAME: mysql
And
{
...
host: 'mysql',
...
}
Inside of the container you should reference the container by the name you gave in your docker-compose.yml file.
In this case you should use
DB_HOSTNAME: mysql
After searching and digging up through several googling attempt, the culprit of the problem soon appear. In this context, the database server is not in the same machine. In other words, the MySQL Database Server address is not localhost. So, how can the above MySQL database configuration by default is pointing to localhost address. Well, it seems that if there is no further definition of the host address, it will connect to the localhost address by default. Read the article for further reference about sequelize syntax pattern in this link.
So, in order to solve the problem, just modify the file with the right configuration database. The following is the correction of the configuration database :
const sequelize = require("sequelize")
const db = new sequelize("db_master","db_user","password", {
host : "10.0.2.2",
dialect: "mysql"
});
db.sync({});
module.exports = db;
Actually, the NodeJS application is running in a virtual server. It is a guest machine run in a VirtualBox application. On the other hand, MySQL Database server exist outside the guest machine. It is available in the host machine where the VirtualBox application is running. The host machine IP address is 10.0.2.2. So, in order to connect to MySQL Database Server in the host machine, the IP address of the host is 10.0.2.2.
use your connection string as :
mysql://username:password#mysql:(port_running_on_container)or(exposed_port)/db_name
Answers already exist, but to provide some further explanation:
You can't use 127.0.0.1 (localhost) to access other services/containers since each container will view that as inside itself. When running docker-compose, all your services will be entered into the same docker network. All services inside the same docker network, are able to reach eachother by service name.
hence, as already stated in previous answers: in your configuration, change db hostname from localhost to mysql.
three things to check before
make sure your service name must be MySQL
in Configure DB_HOST also a MySQL
And your backend service depends on mysql in docker-compose.yml
here is my success code
export const db = new Sequelize(
process.env.DB_NAME,
process.env.DB_USER,
process.env.DB_PASSWORD,
{
port: process.env.DB_PORT,
host:'mysql',
dialect: "mysql",
logging: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
}
);

Not able to connect a rabbitmq docker with appl docker

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 !!

Resources