Express container unable to connect to Mongo Image with Docker-Compose - mongodb

I am trying to connect an express container to MongoDB image with docker compose but the connection is being rejected, I can connect to the db with robomongo. I can't get what is happening, this is the express code that connects it:
mongoose.connect('mongodb://localhost:27017/database')
.then(()=>console.log('connection succesfull to url'))
.catch((err)=>console.error(err));
This is the docker-compose file
version: "3"
services:
backend:
build:
context: ../backend
dockerfile: ${PWD}/images/backend/Dockerfile
container_name: backend
ports:
- "${BACKEND_PORT}:${BACKEND_PORT}"
env_file:
- ./deploy.env
environment:
- PORT=3000
- MONGO_CONNECTION=${MONGO_CONNECTION}
command: npm start
links:
- mongodb
depends_on:
- mongodb
front-app:
build:
context: ../front-app
dockerfile: ${PWD}/images/angular/Dockerfile
container_name: front-app
ports:
- "${FRONTEND_PORT}:4200"
env_file:
- ./deploy.env
command: npm start
mongodb:
image: mongo:3.6
container_name: mongo
volumes:
- "${MONGO_DB_DATA}:/data/db"
- "${MONGO_DB_DATA}:/data/configdb"
ports:
- "27017:27017"
This is the error
backend | { MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
backend | at Pool.<anonymous> (/usr/src/app/node_modules/mongodb-core/lib/topologies/server.js:564:11)
backend | at Pool.emit (events.js:182:13)
backend | at Pool.EventEmitter.emit (domain.js:442:20)
backend | at Connection.<anonymous> (/usr/src/app/node_modules/mongodb-core/lib/connection/pool.js:317:12)
backend | at Object.onceWrapper (events.js:273:13)
backend | at Connection.emit (events.js:182:13)
backend | at Connection.EventEmitter.emit (domain.js:442:20)
backend | at Socket.<anonymous> (/usr/src/app/node_modules/mongodb-core/lib/connection/connection.js:246:50)
backend | at Object.onceWrapper (events.js:273:13)
backend | at Socket.emit (events.js:182:13)
backend | at Socket.EventEmitter.emit (domain.js:442:20)
backend | at emitErrorNT (internal/streams/destroy.js:82:8)
backend | at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
backend | at process._tickCallback (internal/process/next_tick.js:63:19)
backend | name: 'MongoNetworkError',
backend | errorLabels: [ 'TransientTransactionError' ],
backend | [Symbol(mongoErrorContextSymbol)]: {} }

Every process running in docker container thinks that he is "the only one in the world". It means that for this process localhost means: my, container's localhost. And your backend is alone in his container so that's why he cannot find mongodb under localhost.
To fix that problem you should place hostname "mongodb" instead of "localhost" as in docker-compose you can access services using theirs names - it means that mongodb container can also access your backend using "backend" domain.
Please note also that "links" is deprecated in docker and shouldn't be used - it's not required in your configuration as docker-compose gives every service within docker-compose file access to each other using method mentioned above.

Jakub Bujny answer is spot on, I did not understand because it did not include an example. So I am adding one.
mongoose.connect('mongodb://mongodb:27017/database')
.then(()=>console.log('connection succesfull to url'))
.catch((err)=>console.error(err));

Related

Mongo express always crashes in docker-compose

Here is my docker-compose file:
version: "3.1"
services:
mongodb:
container_name: mongodb
image: mongo:latest
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: $$Admin123
MONGO_INITDB_DATABASE: xplorie
# hostname: mongodb
networks:
mynetwork:
ipv4_address: 172.19.0.20
ports:
- 27017:27017
volumes:
- /var/data/mongo:/data/db
mongo-express:
image: mongo-express
environment:
# ME_CONFIG_MONGODB_SERVER: mongodb
ME_CONFIG_MONGODB_PORT: 27017
# ME_CONFIG_MONGODB_AUTH_USERNAME: admin
# ME_CONFIG_MONGODB_AUTH_PASSWORD: $$Admin123
ME_CONFIG_MONGODB_ADMINUSERNAME: admin
ME_CONFIG_MONGODB_ADMINPASSWORD: $$Admin123
# ME_CONFIG_BASICAUTH_USERNAME: admin
# ME_CONFIG_BASICAUTH_PASSWORD: $$Admin123
# networks:
# mynetwork:
# ipv4_address: 172.19.0.21
volumes:
- /var/data/mongoclient:/data/db
depends_on:
- mongodb
ports:
- "3300:3000"
restart: always
networks:
mynetwork:
driver: bridge
ipam:
config:
- subnet: 172.19.0.0/24
gateway: 172.19.0.1
but when I run this mongo express always crashes. this is the log:
mongo-express_1 | Welcome to mongo-express
mongo-express_1 | ------------------------
mongo-express_1 |
mongo-express_1 |
mongo-express_1 | (node:7) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
mongo-express_1 | Could not connect to database using connectionString: mongodb://mongo:27017"
mongo-express_1 | (node:7) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [mongo:27017] on first connect [Error: getaddrinfo EAI_AGAIN mongo
mongo-express_1 | at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26) {
mongo-express_1 | name: 'MongoNetworkError'
mongo-express_1 | }]
mongo-express_1 | at Pool.<anonymous> (/node_modules/mongodb/lib/core/topologies/server.js:441:11)
mongo-express_1 | at Pool.emit (events.js:314:20)
mongo-express_1 | at /node_modules/mongodb/lib/core/connection/pool.js:564:14
mongo-express_1 | at /node_modules/mongodb/lib/core/connection/pool.js:1000:11
mongo-express_1 | at /node_modules/mongodb/lib/core/connection/connect.js:32:7
mongo-express_1 | at callback (/node_modules/mongodb/lib/core/connection/connect.js:300:5)
mongo-express_1 | at Socket.<anonymous> (/node_modules/mongodb/lib/core/connection/connect.js:330:7)
mongo-express_1 | at Object.onceWrapper (events.js:421:26)
mongo-express_1 | at Socket.emit (events.js:314:20)
mongo-express_1 | at emitErrorNT (internal/streams/destroy.js:92:8)
mongo-express_1 | at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
mongo-express_1 | at processTicksAndRejections (internal/process/task_queues.js:84:21)
mongo-express_1 | (node:7) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
mongo-express_1 | (node:7) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
deploy_mongo-express_1 exited with code 0
You have the mongo database container on one network (user defined) and the mongo-express container on the default bridge network. So they can't talk to each other.
Also, the hostname of the mongo db container is mongodb, so you should comment that back in.
Mongo express listens on port 8081, so that's the port you should map.
I'd just use the default bridge network and do something like this
version: "3.1"
services:
mongodb:
container_name: mongodb
image: mongo:latest
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: $$Admin123
MONGO_INITDB_DATABASE: xplorie
ports:
- 27017:27017
volumes:
- /var/data/mongo:/data/db
mongo-express:
image: mongo-express
environment:
ME_CONFIG_MONGODB_SERVER: mongodb
ME_CONFIG_MONGODB_ADMINUSERNAME: admin
ME_CONFIG_MONGODB_ADMINPASSWORD: $$Admin123
# ME_CONFIG_BASICAUTH_USERNAME: admin
# ME_CONFIG_BASICAUTH_PASSWORD: $$Admin123
depends_on:
- mongodb
ports:
- "3300:8081"
restart: always
You should then be able to access Mongo express on http://localhost:3300/.
Be aware that Mongo will not create a database for you because you don't have any initialization scripts. From the docs: 'MongoDB is fundamentally designed for "create on first use", so if you do not insert data with your JavaScript files, then no database is created.'
Another thing is that Mongo Express is still alpha software and it tries to connect to the database immediately when it starts and that connection often fails because Mongo needs a little time to be ready. By setting restart: always as you have, you'll restart Express until the connection succeeds. But you might see a failed container or two on startup.

Default Docker Compose for MongoDB and Mongo-Express times out on Debian

I am trying to setup a docker-compose setup to run MongoDB and Mongo-Express on a Debian virtual machine.
I've read up on problems with volumes, same docker networks, setting ME_CONFIG_MONGODB_SERVER to the Mongodb container name and having problems with UFW.
This is my current docker-compose.yml
version: '3.7'
services:
mongodb:
image: mongo
container_name: mongodb
restart: always
ports:
- '27017:27017'
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=password
- MONGO_INITDB_DATABASE=default
networks:
- mongo-compose-network
volumes:
- /home/paul/mongodbdocker/data:/data/db
mongo-express:
image: mongo-express
container_name: mongo-express
restart: always
depends_on:
- mongodb
networks:
- mongo-compose-network
environment:
- ME_CONFIG_MONGODB_ADMINUSERNAME=admin
- ME_CONFIG_MONGODB_ADMINPASSWORD=password
- ME_CONFIG_MONGODB_SERVER=mongodb
- ME_CONFIG_BASICAUTH_USERNAME=admin
- ME_CONFIG_BASICAUTH_PASSWORD=password
ports:
- '8081:8081'
volumes:
- /home/paul/mongodbdocker/data:/data/db
networks:
mongo-compose-network:
driver: bridge
I have disabled the UFW firewall with sudo ufw disable and also edited the ufw configuration as described in here What is the best practice of docker + ufw under Ubuntu from Feng.
The MongoDB starts up, but sadly mongo-express fails on first connection with this error:
mongo-express | Welcome to mongo-express
mongo-express | ------------------------
mongo-express |
mongo-express |
mongo-express | (node:8) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
mongo-express | Could not connect to database using connectionString: mongodb://admin:password#mongodb:27017/"
mongo-express | (node:8) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [mongodb:27017] on first connect [MongoNetworkTimeoutError: connection timed out
mongo-express | at connectionFailureError (/node_modules/mongodb/lib/core/connection/connect.js:362:14)
mongo-express | at Socket.<anonymous> (/node_modules/mongodb/lib/core/connection/connect.js:330:16)
mongo-express | at Object.onceWrapper (events.js:420:28)
mongo-express | at Socket.emit (events.js:314:20)
mongo-express | at Socket._onTimeout (net.js:483:8)
mongo-express | at listOnTimeout (internal/timers.js:554:17)
mongo-express | at processTimers (internal/timers.js:497:7)]
mongo-express | at Pool.<anonymous> (/node_modules/mongodb/lib/core/topologies/server.js:441:11)
mongo-express | at Pool.emit (events.js:314:20)
mongo-express | at /node_modules/mongodb/lib/core/connection/pool.js:564:14
mongo-express | at /node_modules/mongodb/lib/core/connection/pool.js:1000:11
mongo-express | at /node_modules/mongodb/lib/core/connection/connect.js:32:7
mongo-express | at callback (/node_modules/mongodb/lib/core/connection/connect.js:300:5)
mongo-express | at Socket.<anonymous> (/node_modules/mongodb/lib/core/connection/connect.js:330:7)
mongo-express | at Object.onceWrapper (events.js:420:28)
mongo-express | at Socket.emit (events.js:314:20)
mongo-express | at Socket._onTimeout (net.js:483:8)
mongo-express | at listOnTimeout (internal/timers.js:554:17)
mongo-express | at processTimers (internal/timers.js:497:7)
mongo-express | (node:8) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
mongo-express | (node:8) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Unable to connect to mongodb as docker compose service from another service

when I launch my application using docker-compose, I get an error that my application cannot connect to the database, although the port is exposed and they are in the same network...
This is my docker-compose.yml file:
version: '3'
volumes:
db-data:
driver: local
mongo-config:
driver: local
services:
pulseq-mongodb:
image: mongo:latest
container_name: server-mongodb
restart: always
networks:
- server-net
ports:
- "27017:27017"
expose:
- 27017
volumes:
- db-data:/data/db
- mongo-config:/data/configdb
server:
image: my-server:0.0.1-pre-alpha.1
container_name: server
restart: always
networks:
- server-net
ports:
- "8080:8080"
depends_on:
- server-mongodb
networks:
server-net:
driver: bridge
I'm getting the following error on startup:
server | 2021-11-01 13:05:10.409 INFO 1 --- [localhost:27017] org.mongodb.driver.cluster : Exception in monitor thread while connecting to server localhost:27017
server |
server | com.mongodb.MongoSocketOpenException: Exception opening socket
server | at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-4.2.3.jar:na]
server | at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:143) ~[mongodb-driver-core-4.2.3.jar:na]
server | at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:188) ~[mongodb-driver-core-4.2.3.jar:na]
server | at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:144) ~[mongodb-driver-core-4.2.3.jar:na]
server | at java.base/java.lang.Thread.run(Unknown Source) ~[na:na]
I tried to use many solutions, but nothing helped me. Any answer will be helpful.
Thanks.
I fixed this by using the container name, instead of localhost in the application configuration.

Mongo-db container shuts down after 30 s

I am developping a web app which has two containers the first container is a web app developed in flask and the second a mongodb image. I want to run them at the same time so I have written the following docker-compose.yml
version: '3.7'
services:
flask:
build: .
depends_on:
- mongo
ports:
- "5000:5000"
volumes:
- ./flask:/flask
mongo:
image: mongo:latest
ports:
- "27017:27017"
volumes:
- ./dump:/dump # data
- ./datos_db:/data/db # persistance database
First I run $docker-compose build with no errors,then I get the following error when I run $ docker-compose up:
mongo_1 | 2019-10-30T16:18:47.420+0000 error connecting to host: could not connect to server: server selection error: server selection timeout
mongo_1 | current topology: Type: Single
mongo_1 | Servers:
mongo_1 | Addr: localhost:27017, Type: Unknown, State: Connected, Average RTT: 0, Last error: connection(localhost:27017[-121]) connection is closed
mongo_1 |
practica4_mongo_1 exited with code 1
As I understand it the container waits too much time for localhost:271017 to be open and decides to shut down. (I have also tried with port 49155)
Is there anything I am missing and that makes my docker crash?

Mongo-Express: failed to connect to server [mongo:27017] on first connect

I'm trying to run the simplest container of mongo and mongo-express using docker-compose. I have faced with many errors that will be explained later on.
I have tried the following docker-compose configurations:
1.
version: '2'
services:
mongo:
image: mongo:latest
mongo-express:
image: mongo-express:latest
ports:
- 8082:8081
2.
version: '2'
services:
mongo:
image: mongo:latest
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: root
ports:
- 27017:27017
volumes:
- db-data:/data/db
- mongo-config:/data/configdb
mongo-express:
image: mongo-express
restart: always
ports:
- 8081:8081
volumes:
db-data:
mongo-config:
and etc. But all of them have the following common error whenever I execute docker-compose -f docker-compose.yml up:
mongo-express_1 | Mongo Express server listening at http://0.0.0.0:8081
mongo-express_1 | Server is open to allow connections from anyone (0.0.0.0)
mongo-express_1 | basicAuth credentials are "admin:pass", it is recommended you change this in your config.js!
mongo-express_1 |
mongo-express_1 | /node_modules/mongodb/lib/server.js:265
mongo-express_1 | process.nextTick(function() { throw err; })
mongo-express_1 | ^
mongo-express_1 | MongoError: failed to connect to server [mongo:27017] on first connect
mongo-express_1 | at Pool.<anonymous> (/node_modules/mongodb-core/lib/topologies/server.js:326:35)
mongo-express_1 | at emitOne (events.js:116:13)
mongo-express_1 | at Pool.emit (events.js:211:7)
mongo-express_1 | at Connection.<anonymous> (/node_modules/mongodb-core/lib/connection/pool.js:270:12)
mongo-express_1 | at Object.onceWrapper (events.js:317:30)
mongo-express_1 | at emitTwo (events.js:126:13)
mongo-express_1 | at Connection.emit (events.js:214:7)
mongo-express_1 | at Socket.<anonymous> (/node_modules/mongodb-core/lib/connection/connection.js:175:49)
mongo-express_1 | at Object.onceWrapper (events.js:315:30)
mongo-express_1 | at emitOne (events.js:116:13)
I have searched this issue all over the internet and github repositories and tried the other solutions, but none of them worked appropriately.
link1 | link2 | link3 | link4 | etc.
First I have run docker stop $(docker ps -a -q) and then changed the docker-compose.yml file to the following content:
version: '2'
services:
mongo:
image: mongo:3.4
container_name: mongo
ports:
- '27017:27017'
volumes:
- '/data/configdb:/data/configdb'
- '/data/db:/data/db'
mongo-express:
image: mongo-express:0.49.0
container_name: mongo_express
depends_on:
- 'mongo'
ports:
- '5050:8081'
environment:
- 'ME_CONFIG_OPTIONS_EDITORTHEME=ambiance'
docker run -d
-p 8081:8081
--name mongo-express
-e ME_CONFIG_MONGODB_ADMINUSERNAME=**<username>**
-e ME_CONFIG_MONGODB_ADMINPASSWORD=**<password>**
--net **<mongo network name>**
-e ME_CONFIG_MONGODB_SERVER=**<mongodb container name>**
-e ME_CONFIG_OPTIONS_EDITORTHEME=ambiance
mongo-express