Post image

Writing front-end or back-end code does not simply develop your web application. Deployment of your web application is a crucial part of the development process, so after writing the code you have to deploy the system.

In this tutorial, we are going to see how to deploy a mongo database server on an AWS ec2 instance.

Creating an ec2 instance
  1. We'll start with launching a new instance through AWS console.
  2. Go to your ec2 console, click on Launch Instance. Next choose an AMI, here we'll chose 'Amazon Linux AMI', then choose your instance type, let's choose 't2.small', next configure your instance details, now it's time to add some storage say 12GiB as /dev/sdb device, next add tags and configure security groups and launch instance.
Setting up the Instance

After successfully launching the instance, ssh to the instance, update installed packages, add the MongoDB yum repo, and install MongoDB:

echo "[mongodb-org-3.2]  
name=MongoDB Repository  
gpgkey=" |  
  sudo tee -a /etc/yum.repos.d/mongodb-org-3.2.repo
sudo yum -y update && sudo yum install -y mongodb-org-server \  
    mongodb-org-shell mongodb-org-tools

Next, create/configure the mount point for data volume, mount volume & set ownership:

sudo mkdir /data  
sudo mkfs.ext4 /dev/xvdb  
echo '/dev/xvdb /data ext4 defaults,auto,noatime,noexec 0 0' | sudo tee -a /etc/fstab  
sudo mount /data  
sudo chown mongod:mongod /data  

Now open /etc/mongod.conf and set dbpath = /data

By default Amazon Linux uses ulimit settings that are not appropriate for MongoDB. To setup ulimit to match the documented ulimit settings, run the following command:

echo '* soft nofile 64000  
* hard nofile 64000
* soft nproc 64000
* hard nproc 64000' | sudo tee /etc/security/limits.d/90-mongodb.conf

By default read ahead settings on EC2 are not optimised for MongoDB, so use this command:
sudo blockdev --setra 32 /dev/xvdb

To make this change persistent across system boot, run the following command:
echo 'ACTION=="add", KERNEL=="xvdb", ATTR{bdi/read_ahead_kb}="16"' | sudo tee -a /etc/udev/rules.d/85-ebs.rules

To start mongod, run the following command:
sudo service mongod start

This will start your mongo server, but still you can't connect to your mongo server using the public IP of your instance, for that you have to open /etc/mongod.conf.
Go to the line where bindIp: is written, comment this line out and add a new line bindIp:
Now you can access mongo using the public IP of your ec2 instance.

Have fun using mongo with your application. Cheers.