DEV Community

Zobaidul Kazi for Kazi Byte

Posted on • Updated on

To create and set up a YAML file for MongoDB and Mongoose connection on localhost, follow these steps:

To create a docker-compose.yaml file that sets up MongoDB and an email service, we can use Docker containers for MongoDB and a Node.js application that connects to MongoDB and sends emails. For the email service, we can use Nodemailer with a transport service like SendGrid or Mailgun.

Here’s how you can create the docker-compose.yaml and necessary files:

Step 1: Create the docker-compose.yaml File

Create a file named docker-compose.yaml with the following content:

version: '3.8'

services:
  mongo:
    image: mongo:latest
    container_name: mongo
    ports:
      - '27017:27017'
    volumes:
      - mongo-data:/data/db

  node-app:
    build: .
    container_name: node-app
    ports:
      - '3000:3000'
    depends_on:
      - mongo
    environment:
      - MONGO_URI=mongodb://mongo:27017/your_database_name
      - NODE_ENV=development
      - SMTP_HOST=smtp.your-email-provider.com
      - SMTP_PORT=587
      - SMTP_USER=your-email@example.com
      - SMTP_PASS=your-email-password

volumes:
  mongo-data:
Enter fullscreen mode Exit fullscreen mode

Step 2: Create the Dockerfile

Create a file named Dockerfile in the same directory with the following content to set up the Node.js application:

# Use the official Node.js image.
FROM node:14

# Create and change to the app directory.
WORKDIR /usr/src/app

# Copy application dependency manifests to the container image.
COPY package*.json ./

# Install dependencies.
RUN npm install

# Copy the local code to the container image.
COPY . .

# Run the web service on container startup.
CMD [ "node", "index.js" ]
Enter fullscreen mode Exit fullscreen mode

Step 3: Create the Node.js Application

Create a file named index.js with the following content to connect to MongoDB and send emails:

const mongoose = require('mongoose');
const nodemailer = require('nodemailer');
const express = require('express');
const bodyParser = require('body-parser');
require('dotenv').config();

// Express setup
const app = express();
app.use(bodyParser.json());

// MongoDB connection
const mongoURI = process.env.MONGO_URI;

mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('Successfully connected to MongoDB'))
  .catch(err => console.error('Error connecting to MongoDB:', err));

// Nodemailer setup
const transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST,
  port: process.env.SMTP_PORT,
  secure: false, // true for 465, false for other ports
  auth: {
    user: process.env.SMTP_USER,
    pass: process.env.SMTP_PASS,
  },
});

// Endpoint to send email
app.post('/send-email', (req, res) => {
  const { to, subject, text } = req.body;

  const mailOptions = {
    from: process.env.SMTP_USER,
    to,
    subject,
    text,
  };

  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      return res.status(500).send(error.toString());
    }
    res.status(200).send('Email sent: ' + info.response);
  });
});

// Start the server
const port = 3000;
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

Step 4: Create the .env File

Create a file named .env to store environment variables for your application:

MONGO_URI=mongodb://mongo:27017/your_database_name
SMTP_HOST=smtp.your-email-provider.com
SMTP_PORT=587
SMTP_USER=your-email@example.com
SMTP_PASS=your-email-password
Enter fullscreen mode Exit fullscreen mode

Step 5: Create the package.json File

Create a file named package.json to define your Node.js project and its dependencies:

{
  "name": "node-docker-app",
  "version": "1.0.0",
  "description": "Node.js app with MongoDB and Nodemailer",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "body-parser": "^1.19.0",
    "dotenv": "^16.0.0",
    "express": "^4.17.1",
    "mongoose": "^5.12.3",
    "nodemailer": "^6.6.3"
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Build and Run the Docker Containers

In your terminal, navigate to the directory containing the docker-compose.yaml file and run:

docker-compose up --build
Enter fullscreen mode Exit fullscreen mode

This command will build the Node.js application container, start MongoDB and the Node.js application, and set up the necessary environment variables.

Your Node.js application should now be able to connect to MongoDB and send emails using Nodemailer.

Top comments (1)

Collapse
 
kalkwst profile image
Info Comment hidden by post author - thread only accessible via permalink
Kostas Kalafatis

Hey there!

While we appreciate you sharing posts here, please see DEV's Content Policy available in our Terms and be careful not to share content that is too promotional. The terms state:

Users must make a good-faith effort to share content that is on-topic, of high-quality, and is not designed primarily for the purposes of promotion or creating backlinks.

Going forward, be careful to avoid sharing articles that are too promotional in nature. While it's generally okay to promote your product, business, personal brand, etc., just make sure that the content you share has value beyond promotion.

If you balance out any promotional materials with helpful tutorials, walkthroughs, or other information, then your post should fit just fine. But, if you continue sharing heavily promotional material, it's likely that our moderators will downvote your content, making it less discoverable in our feeds and potentially deindexed from search engines. If your content is regularly downvoted by our mods, this will alert our admin, who may take action to remove your content and/or suspend your account.

We hope you continue to enjoy DEV and share content, but please keep the promotional material to a minimum and keep in mind that the community here is made up of software devs who are primarily trying to help out and learn from one another!

Some comments have been hidden by the post's author - find out more