nodejs with docker and postgress: Error: getaddrinfo ENOTFOUND - node.js

Hello I don't know what else to do to resolve this error:
ci-api | Error: getaddrinfo ENOTFOUND ${DB_HOST}
ci-api | at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26) {
ci-api | errno: 'ENOTFOUND',
ci-api | code: 'ENOTFOUND',
ci-api | syscall: 'getaddrinfo',
ci-api | hostname: '${DB_HOST}'
ci-api | }
I have a .env file with the following variables:
.env file:
SERVER_PORT=4000
DB_HOST=db-pg
DB_PORT=5432
DB_USER=spirit
DB_PASS=api
DB_NAME=emasa_ci
DockerFile:
#building code
FROM node:lts-alpine
ADD https://github.com/ufoscout/docker-compose-wait/releases/download/2.7.3/wait /wait
RUN chmod +x /wait
RUN mkdir -p /home/node/api && chown -R node:node /home/node/api
WORKDIR /home/node/api
COPY ormconfig.json .env package.json yarn.* ./
USER node
RUN yarn
COPY --chown=node:node . .
EXPOSE 4000
**My `docker-compose`:**
version: '3.7'
services:
db-pg:
image: postgres:12
container_name: db-pg
ports:
- '${DB_PORT}:5432'
environment:
ALLOW_EMPTY_PASSWORD: 'no'
POSTGRES_USER: ${DB_USER}
POSTGRES_PASSWORD: ${DB_PASS}
POSTGRES_DB: ${DB_NAME}
volumes:
- ci-postgres-data:/data
ci-api:
build: .
container_name: ci-api
volumes:
- .:/home/node/api
ports:
- '${SERVER_PORT}:${SERVER_PORT}'
depends_on:
- db-pg
command: sh -c "/wait && yarn dev"
environment:
WAIT_HOSTS: db-pg:5432
logging:
driver: 'json-file'
options:
max-size: '10m'
max-file: '5'
volumes:
ci-postgres-data:
And, this is my ORM CONFIG:
{
"type": "postgres",
"host": "${DB_HOST}",
"port": "${DB_PORT}",
"username": "${DB_USER}",
"password": "${DB_PASS}",
"database": "${DB_NAME}",
"synchronize": true,
"logging": false,
"entities": ["dist/src/entity/**/*.js"],
"migrations": ["dist/src/migration/**/*.js"],
"subscribers": ["dist/src/subscriber/**/*.js"],
"cli": {
"entitiesDir": "dist/src/entity",
"migrationsDir": "dist/src/migration",
"subscribersDir": "dist/src/subscriber"
}
}
I can't imagine the reason for this error, I basically added a script for the node to start after the start of my Postgres where db-pg is my Postgres image name.
I can't imagine what went wrong, could someone help me with this?
P.S.: I use typescript/typeorm

{
"type": "postgres",
"host": "db-pg",
"port": 5432,
"username": "spirit",
"password": "api",
"database": "emasa_ci",
"synchronize": true,
"logging": false,
"entities": ["dist/src/entity/**/*.js"],
"migrations": ["dist/src/migration/**/*.js"],
"subscribers": ["dist/src/subscriber/**/*.js"],
"cli": {
"entitiesDir": "dist/src/entity",
"migrationsDir": "dist/src/migration",
"subscribersDir": "dist/src/subscriber"
}
}
the problem was in my
ormconfig.json (was using .env)

Related

Docker Node MongoDB AuthenticationFailed: SCRAM-SHA-1 authentication failed, storedKey mismatch

I am posting it here as I am run out of options.
I am trying to make a connection from my node app to the mongodb.
I am getting AuthenticationFailed: SCRAM-SHA-1 authentication failed, storedKey mismatch
My local environment works 100%. I dumped my local MongoDB (the app database and admin too) into the docker container.
I created my docker-compose.yml as below:
version: "1.0"
services:
mongodb:
image: mongo:3.4.7
container_name: MongoDB2
restart: unless-stopped
ports:
- '27017:27017'
app:
links:
- mongodb
depends_on:
- mongodb
image: eamello/gsd:myCore
ports:
- '8087:8087'
stdin_open: true
tty: true
volumes:
db:
networks:
node-webapp-network:
driver: bridge
My config.json file, which has the database connection details:
"myCore": {
"database": {
"url": "mongodb://mongodb:27017/myCore",
"options": {
"db": {
"native_parser": true
},
"server": {
"poolSize": 100,
"socketOptions": {
"keepAlive": 1000,
"connectTimeoutMS": 30000
}
},
"replset": {},
"user": "myAdmin",
"pass": "/WnUU5Jqithypb9970AfIQ==",
"auth": {
"authdb": "admin"
},
"queryLevel":{
"common":{
"maxTimeMS": 15000
}
}
}
},
I am 100% sure the user created in my admin database has the same password.
I check and rechecked several times.
I also tried to add my user via javascript file... it looks like the javascript was never executed.
db.createUser(
{
user: "myAdmin",
pwd: "/WnUU5Jqithypb9970AfIQ==",
roles: [
{
role: "userAdmin", db: "myCore"
},
{
role: "readWrite", db: "myCore"
}
]
}
);
As I can manage my MongoDB via Compass, I left this javascript aside.
Does anyone have any clue why I am getting AuthenticationFailed: SCRAM-SHA-1 authentication failed, storedKey mismatch?
I changed some names above as this is a company issue. Thanks.

MongoServerSelectionError: getaddringo EAI_AGAIN mongo

I'm getting an error when my server is connecting to the MongoDB database. Both the server and mongoDB are in containers
The docker-compose files are as follows:
docker-compose.yml
version: '3'
services:
client:
build:
context: ./client
dockerfile: Dockerfile
ports:
- 3001:3001
networks:
- mern-network
volumes:
- ./client/src:/usr/app/src
- ./client/public:/usr/app/public
depends_on:
- server
environment:
- REACT_APP_SERVER=http://localhost:5001
# - CHOKIDAR_USEPOLLING=true
# container 1: backend node server
server:
build:
context: ./server
dockerfile: Dockerfile
ports:
- '5001:5001'
networks:
- mern-network
environment:
- PORT=5001
depends_on:
- mongo
# container 2: database
mongo:
image: mongo:4.4.13
networks:
- mern-network
environment:
- MONGO_INITDB_ROOT_USERNAME=docker_mongo
- MONGO_INITDB_ROOT_PASSWORD=password
volumes:
- mongo-db:/data/db
networks:
mern-network:
driver: bridge
volumes:
mongo-db:
docker-compose.dev.yml
version: '3'
services:
# container 3: client, dev settings
client:
command: npm start
# container 1: server, dev setting
server:
build:
args:
BUILD_ENV: development
volumes:
- ./server/:/app
# - ./server/app/node_modules
environment:
- BUILD_ENV=development
- MONGO_USER=docker_mongo
- MONGO_PASSWORD=password
- SESSION_SECRET=secret123456890qwerty
command: npm run dev
# container 2: database, dev settings
mongo:
environment:
- MONGO_INITDB_ROOT_USERNAME=docker_mongo
- MONGO_INITDB_ROOT_PASSWORD=password
I have no problems accessing into the mongodb database when I inspect the container using docker exec -it but error when I connect with node. I've tried many versions of mongoose still gives me same error.
MongoServerSelectionError: getaddrinfo EAI_AGAIN mongo
at Timeout._onTimeout (/home/user/git_folder/project/server/node_modules/mongodb/lib/sdam/topology.js:312:38)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'mongo:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: 'mongo', port: 27017 },
address: 'mongo:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 53541928,
lastWriteDate: 0,
error: MongoNetworkError: getaddrinfo EAI_AGAIN mongo
at connectionFailureError (/home/user/git_folder/project/server/node_modules/mongodb/lib/cmap/connect.js:375:20)
at Socket.<anonymous> (/home/user/git_folder/project/server/node_modules/mongodb/lib/cmap/connect.js:295:22)
at Object.onceWrapper (node:events:640:26)
at Socket.emit (node:events:520:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
},
code: undefined
}

[SequelizeConnectionRefusedError]: connect ECONNREFUSED 127.0.0.1:3306. using sequelize in docker [duplicate]

This question already has answers here:
Docker - SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306
(6 answers)
Closed last year.
I'm new to docker. I tried to find other solution same as mine but it didn't work at all.
When run docker compose up, it responded connection error. Here's my full code Link
error
errno: -111, server-api-1 | code: 'ECONNREFUSED', server-api-1 |
syscall: 'connect', server-api-1 | address: '127.0.0.1',
server-api-1 | port: 3306, server-api-1 | fatal: true
server-api-1 | }, server-api-1 | original: Error: connect
ECONNREFUSED 127.0.0.1:3306 server-api-1 | at
TCPConnectWrap.afterConnect [as oncomplete] (node:net:1161:16) {
server-api-1 | errno: -111, server-api-1 | code:
'ECONNREFUSED', server-api-1 | syscall: 'connect', server-api-1
| address: '127.0.0.1', server-api-1 | port: 3306,
server-api-1 | fatal: true server-api-1 | } server-api-1 | }
config.json
{
"development": {
"username": "root",
"password": "Password",
"database": "vc_chat",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
Dockerfile
FROM node:16-alpine
WORKDIR /app/server
ADD server /app/server
RUN npm install
COPY . .
CMD [ "npm", "start" ]
docker-compose.yml
version: "3.9"
services:
# Mysql
mysql_db:
container_name: db_container
image: mysql:latest
command: --default-authentication-plugin=mysql_native_password
restart: always
environment:
MYSQL_DATABASE: "vc_chat"
MYSQL_USER: "root"
MYSQL_PASSWORD: "Password"
MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
DB_HOSTNAME: mysql
volumes:
- mysql_db:/var/lib/mysql
api:
build: .
ports:
- 4000:4000
environment:
- EMAIL= "test#gmail.com"
- PASSWORD= "test123"
- JWT_SECRET= "DENNY"
depends_on:
- mysql_db
volumes:
mysql_db: {}
You can't use 127.0.0.1 (localhost) in the context of docker since each container will view that as inside itself. When running docker-compose, the services will be entered into the same docker network. In that docker network, the services are reachable by the contianer name,
so the database should be reachable at db_container:3306
(meaning, you will have to change the confguration for db host in config.json)

use docker-compose to build frontend and backend ,then call api from frontend but fail

i build frontend (next.js) and backend(express) ,and try to call backend api but fail.
the following is my code:
dockerFile from backend(listen port 3001)
FROM node:16.13-alpine
WORKDIR /backend/
COPY . .
ENV NODE_ENV=production
EXPOSE 3001
RUN npm install -g npm#8.3.0\
&& npm install\
&& npm install typescript -g\
&& npx tsc
CMD [ "node", "./build/index.js" ]
dockerFile from frontend(listen port 3000), api baseUrl is http://node:80/
FROM node:16.13-alpine
WORKDIR /frontend/
ENV PORT 3000
COPY package.json ./
COPY yarn.lock ./
RUN npm install
COPY . ./
EXPOSE ${PORT}
ENTRYPOINT ["npm", "run","dev"]
docker-compose.yml
version: "3.9"
services:
node:
env_file: "./back/.env"
volumes:
- ./test:/backend/test
- ./back/node_modules:/backend/src/node_modules
build:
context: ./back
ports:
- "80:3001"
expose:
- 80
networks:
- testNetwork
next:
depends_on:
- node
build:
context: ./front
ports:
- "3000:3000"
networks:
- testNetwork
volumes:
- ./front/node_modules:/frontend/src/node_modules
- ./test:/frontend/test
networks:
testNetwork:
i can access localhost:80 ,which is working.
but when i access localhost:3000, i got error by next.js as below
next_1 | Error: connect ECONNREFUSED 172.21.0.2:80
next_1 | at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1161:16) {
next_1 | type: 'Error',
next_1 | config: {
next_1 | transitional: {
next_1 | silentJSONParsing: true,
next_1 | forcedJSONParsing: true,
next_1 | clarifyTimeoutError: false
next_1 | },
next_1 | transformRequest: [ null ],
next_1 | transformResponse: [ null ],
next_1 | timeout: 0,
next_1 | xsrfCookieName: 'XSRF-TOKEN',
next_1 | xsrfHeaderName: 'X-XSRF-TOKEN',
next_1 | maxContentLength: -1,
next_1 | maxBodyLength: -1,
next_1 | headers: {
next_1 | Accept: 'application/json, text/plain, */*',
next_1 | 'User-Agent': 'axios/0.23.0'
next_1 | },
next_1 | baseURL: 'http://node:80/',
next_1 | method: 'get',
next_1 | url: 'getStaticPath/onlyCategoryRoute'
next_1 | },
next_1 | code: 'ECONNREFUSED',
next_1 | status: null
next_1 | }
thanks for looking
Your application is attempting to connect to port 80 within a docker container but you have port 80 available only on the host computer, within the docker container, it is port 3001.

docker-compose: Connect to mongodb using node

I'm looking for some help on how I can connect to a mongodb using node in two different containers.
I have three services set up in my docker compose:
webserver (irrelevant to question)
nodeJs
mongo database
The nodejs container is essentially an api which I can use to communicate with mongodb:
require('dotenv').config();
const express = require('express');
const cors = require('cors')
const app = express();
var MongoClient = require('mongodb').MongoClient;
var mongodb = require('mongodb');
app.use(express.json())
app.use(cors())
app.post('/api/fetch-items', (req, res) => {
if (req.headers.apikey !== process.env.API_KEY) return res.sendStatus(401)
// URL is in the format: mongodb://user:pwd#database:27017
MongoClient.connect(process.env.MONGODB_URL, function(err, db) {
if (err) return res.status(500).send(err);
var dbo = db.db("db");
dbo.collection("col").find({}).toArray(function(err, result) {
if (err) return res.status(500).send(err);
db.close();
return res.status(200).send(result);
});
});
})
app.listen(4000)
This all works perfectly fine if I run node as a standalone container (not using docker-compose) and use localhost in the URL.
However, when I use the image in docker-compose I receive the response:
{
"name": "MongoNetworkError"
}
when sending a request to the API.
I am currently using the hostname 'database' in the URL and this does not work. I have also tried using localhost.
There are also no errors as a result of the command node server.
If needed my Dockerfile for the node server is:
FROM node:10-alpine
RUN mkdir -p /home/node/app/node_modules && chown -R node:node /home/node/app
WORKDIR /home/node/app
COPY package*.json ./
RUN chown node:node ./package*.json
USER node
RUN npm install
COPY --chown=node:node . .
EXPOSE 4000
CMD [ "node", "server" ]
My docker-compose.yml file:
version: "3.1"
services:
mongodb:
image: mongo
restart: always
container_name: database
ports:
- 27017:27017
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: xxxxxxxx
# Web server stuff
node:
image: created-node-server
container_name: node
ports:
- 4000:4000
Finally, the output of docker network inspect:
[
{
"Name": "network_default",
"Id": "3e51a90a23f2785cfc405243ad4c73991852f52826fd1cd0b14da5d4eaa180e4",
"Created": "2021-01-12T01:07:42.656013002Z",
"Scope": "local",
"Driver": "bridge",
"EnableIPv6": false,
"IPAM": {
"Driver": "default",
"Options": null,
"Config": [
{
"Subnet": "172.23.0.0/16",
"Gateway": "172.23.0.1"
}
]
},
"Internal": false,
"Attachable": true,
"Ingress": false,
"ConfigFrom": {
"Network": ""
},
"ConfigOnly": false,
"Containers": {
"418876a06c3f8fa430804ae77c66cca986a49dbc88374266346463f7f448baa7": {
"Name": "database",
"EndpointID": "ac08c5a439edd43e612723d269714e9dfbae29dbdb50790b61c66207287d70c8",
"MacAddress": "02:42:ac:17:00:04",
"IPv4Address": "172.23.0.4/16",
"IPv6Address": ""
},
"7b6dcbb8f76618575c988a026ac0308075a116f79a2e58d8a146e33fb5d7674c": {
"Name": "node",
"EndpointID": "e6beb412a2fe97ae7d04d2484a7ca3634bfa37c82680becc412d1f44502da72f",
"MacAddress": "02:42:ac:17:00:03",
"IPv4Address": "172.23.0.3/16",
"IPv6Address": ""
},
"f2ea250bccdb2c6a0c4d7818912ddbf29196eff072dad699e8dbcef466cd38a3": {
"Name": "webserver",
"EndpointID": "f6617aab4001032069e68300c5303fa730f3458e2fe0092ace45a9f67e16d7c5",
"MacAddress": "02:42:ac:17:00:02",
"IPv4Address": "172.23.0.2/16",
"IPv6Address": ""
}
},
"Options": {},
"Labels": {
"com.docker.compose.network": "default",
"com.docker.compose.project": "proj",
"com.docker.compose.version": "1.27.4"
}
}
]
Essentially, I am retrieving the MongoNetworkError when trying to communicate with mongodb through node, both of which are docker containers created using docker-compose.
I hope all the above makes sense, sorry if it is a bit wordy, I have tried to include as much info as possible. Comment if you need any more info
Thanks :)
You just need to include an environmental variable under the node service MONGODB_URL=mongodb://database:27017

Resources