STEP1, Create a Express.js App
terminal
// create directory and initialize app
mkdir express-mongo
cd express-mongo
npm init -y
// create file necessary
touch server.js
touch Dockerfile
touch .dockerignore
// install modules
npm install express mongodb
server.js
server.js
const express = require("express");
const app = express();
const PORT = 3000;
const { MongoClient } = require("mongodb");
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
const uri = "mongodb://root:password@mongodb:27017";
const client = new MongoClient(uri);
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
app.get("/", async (req, res) => {
try {
await client.connect();
const db = client.db("user-account");
const collection = db.collection("users");
const result = await collection.findOne({ userid: 1 }, options);
res.json(result);
} catch (error) {
console.log(error);
} finally {
await client.close();
}
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Dockerfile
Dockerfile
FROM node:alpine3.18
WORKDIR /usr/src/app
COPY . /usr/src/app/
RUN npm install
EXPOSE 3000
CMD [ "node", "server.js" ]
.dockerignore
.dockerignore
node_modules
STEP2, Create a docker-compose.yml
docker-compose.yml
version: "3.9"
services:
node:
build: .
container_name: express_app
ports:
- 3000:3000
restart: always
volumes:
- ./:/usr/src/app
networks:
- mongo-network
depends_on:
- mongodb
mongodb:
image: mongo
container_name: mongo_db
restart: always
ports:
- 27017:27017
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: password
volumes:
- mongo_db:/data/db
- config_db:/data/configdb
networks:
- mongo-network
mongo-express:
image: mongo-express
container_name: mongo_express
restart: always
ports:
- 8081:8081
environment:
ME_CONFIG_OPTIONS_EDITORTHEME: ambiance
ME_CONFIG_MONGODB_ADMINUSERNAME: root
ME_CONFIG_MONGODB_ADMINPASSWORD: password
ME_CONFIG_MONGODB_SERVER: mongodb
networks:
- mongo-network
depends_on:
- mongodb
networks:
mongo-network:
volumes:
mongo_db:
config_db:
STEP3, docker compose up -d
terminal
docker compose up -d
all container is running successfully
STEP4, insert data to mongoDB
create database "user-account"
create collection "users"
STEP5, Access to http://localhost:3000
you can see the data from mongodb successfully!!
STEP6, Down docker compose
terminal
docker compose down