let me take you basics for the trio, mongodb, nodejs and docker (compose). please setup the following simple system, inspect, and try to check which part of your code deviates, then let me know the result.
1- create a new test folder, copy the following compose content to a “compose.yml” file
compose.yml
version: '3.7'
name: "mongo-node-docker"
services:
mongo:
image: mongo:latest
ports:
- "27017:27017"
volumes:
- ./mongo_data:/data/db
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example
nodeapp:
image: node:19-alpine
working_dir: /app
command: "npm start" # "npm install" then "npm start"
ports:
- "8080:8080"
volumes:
- ./nodeapp:/app
depends_on:
- mongo
environment:
MONGODB_ADMINUSERNAME: root
MONGODB_ADMINPASSWORD: example
MONGODB_URL: mongodb://root:example@mongo:27017/
2- create “mongo_data” folder to bind to mongodb data folder. binds are faster to remove than a volumes
3- create “nodeapp” folder. inside create 2 files, “package.json” and “index.js”, then copy following contents
package.json
{
"name": "nodeapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"mongodb": "^4.13.0"
}
}
index.js
const { MongoClient } = require("mongodb");
let uri = process.env.MONGODB_URL;
const client = new MongoClient(uri);
async function run() {
try {
const conn = await client.connect()
console.log("from: ",conn.s.url)
const database = client.db("testdb");
const coll = database.collection('testcoll');
await coll.insertOne({"name":"testname"})
const data = await coll.findOne({});
console.log(data);
} finally {
await client.close();
}
}
run().catch(console.dir);
4- run database server first, as a service: docker compose run -d mongo
5- then run app in foreground: docker compose run --rm nodeapp
- IMPORTANT: you need to run this twice. I use “command” in the compose file, thus you need to first run with
command: "npm install"
for the first run.
6- you should see the following output (different id, though)
from: mongodb://root:example@mongo:27017/
{ _id: new ObjectId("63c5dbffaef20bb1535ec6c1"), name: 'testname' }
you will immediately notice the use of await keyword; when I make the open queries. and app works fine.
if you followed all steps, now compare your app and compose file and see if you can find what differs in these basic steps.
EDIT: I forgot a step in running the app. since I don’t use an image creation step, you need to first run it with having command to be npm install
then second time with npm start
.