Category Archives: Amazon AWS

Access Amazon RDS from AWS Lambda

Recently I was working with serverless application created in NodeJs which was deployed to AWS Lambda. This app is connecting to MySQL database which was deployed to RDS. While I was testing in local machine it worked very well.

AWS Lambda Amazon RDS

After deployed it stopped working. After struggling for half a day I was able to finally make it working. In this blog I am going to mention what it takes to make it working.

Different Security Group is the First Solution

This is really strange, if your Amazon RDS and AWS Lambda function shares the security group it will never connect. Not sure why it’s this way, but to solve the problem.

  1. Create New Security Group and assign it to your Lambda function.
  2. Create Other Security Group and assign it your RDS
  3. Allow MySQL connection in RDS Security Group

To allow MySQL connection, add inbound rules. Select MYSQL/Aurora fromType and allow it from 0.0.0.0/0

Allow VPC Access to Lambda Function

  1. Go to Roles page in IAM consle.
  2. Create new role and add policy AWSLambdaVPCAccessExecutionRole
  3. Assign this role to your Lambda function

Use Connection Pool in Your Code

While using serverless you have to be careful about asynchronous operations. Connection to MySQL is also asynchronous operations. If you do not handle it properly, lambda function will give you timeout as it’s expecting callback function to return result but because it’s async operations it will take time. So you have to explicitly let it know that, there is async operation so wait for it.

So for that create connection pool.

var mysql = require(‘mysql’);
var pool = mysql.createPool({
user : ‘username’,
password : “password”,
database: ‘database’,
host : ‘rds_end_point’
});

Now wait to get connection from the pool.

pool.getConnection((err, connection) => {
connection.query(‘SQL’,function(err, rows, fields) {
const response = {
statusCode: 200,
headers: {
“Access-Control-Allow-Origin” : “*” // Required for CORS support to work
},
body: JSON.stringify({
success: true,
rows: rows
})
};
connection.release();
callback(null, response);
});
})

As you can see in above code we are waiting for getting connection. Once we have the connection we query the database and get the result. After that we invoke the callback and release the connection so it can be used for next requests.

Installing a LAMP Web Server on Amazon EC2

In this blog post we will understand procedures that will help you install the Apache web server with PHP and MySQL support on your Amazon EC2 Ubuntu instance. We will go through procedure, step by step.

Prerequisites

We assume that you have registered for Amazon AWS account. If you have not registered, first of all register for it through this link .

After you have registered login to Amazon AWS account and go to AWS Management Console. From services, go to Amazon EC2

Launch Amazon EC2 Instance

First of all we have to create and launch Amazon EC2 instance. Click on Launch Instance. It will ask you to select Amazon Machine Image in Step 1

 

 

 

 

From here select Ubuntu Server. In next step it will ask you to select instance type. Depending on your application size and traffic, you can choose instance. For now we will go for default selected micro instance.

Click on Review and Launch. It will take you to final step, to review. From there click on Launch. It will show a pop up to create key pair. This will be used to connect with instance using SSH. Create and download key pair and save it to desktop. Now click on Launch Instance.

It will launch instance, once the instance is launched, click on View Instances. Once you click on running instance, it will show you all the details of instance like Public DNS, public IP etc. IP will use to connect with SSH.

Now, instance is up and running, we will connect with SSH and install necessary components.

Connect to instance with SSH

To connect we will use key pair created while we were creating instance. Go to terminal and go to directory, where you downloaded key and run following command.

chmod 400 YourKey.pem

This will change key permission to make it readable. Now connect to instance using public IP of your instance.

ssh -i “YourKey.pem” ubuntu@YourIP

Install Apache and PHP 7.0

sudo apt-get install apache2 php7.0 libapache2-mod-php7.0

Now verify it.

a2query -m php7.0

Load PHP module.

sudo a2enmod php7.0

Restart apache.

sudo service apache2 restart

New version of ubuntu comes with PHP 7 but to access it you have to install php command lines. Run following command.

sudo apt-get install php7.0-cli

Now test it with

php -v

Create Test PHP

Go to your apache root directory with following command

cd /var/www/html

There will be one index.html file. We have to remove this and create new file for testing.

sudo rm index.html

sudo vim index.php

This will open vim editor, press i and now you can type in file. Let’s create simple php file.

<?php
echo “Hello AWS”;
?>

press esc and : and type wq this will save file.

View test PHP file in Browser

To view file in browser, copy the public DNS and paste in browser. But wait it won’t work because Amazon EC2 instances have inbound rules where you have to configure what types of connections can be made to your instance. By default only SSH is allowed, we have to add HTTP connection.

For that go to security groups and in bound rule.

Now refresh browser and you will see Hello AWS message.

.htaccess Doesn’t Work in Amazon AWS EC2 Instance with Ubuntu

Recently I was configuring Laravel application in Amazon AWS EC2 instance which was having Ubuntu and Apache installed. The problem was htacess file was not working so Laravel routes were not working. Instead of parsing laravel routes it always shows error URL not found.

The problem is by default in apache installed on ubuntu doesn’t have .htaccess enabled so first you have to manually enable it in config file and restart apache.

Here are the steps.

1) Login to your EC2 instance with SSH.

ssh -i “Yourkey.pem” ubuntu@yourpublicip

2) Enable Mode Rewrite, this is just incase if it’s not enabled.

sudo a2enmod rewrite

3) Go to following directory.

cd /etc/apache2/sites-available

If you use LS command here you will see following file.

000-default.conf

That’s the file with default apache configuration which are applied to your sites in /var/www/html folder.

4) Open this file for editing.

sudo nano 000-default.conf

5) Add following lines after DocumentRoot /var/www/html line.

<Directory />
     Options FollowSymLinks
     AllowOverride All
</Directory>
<Directory /var/www/html>
     Options Indexes FollowSymLinks MultiViews
     AllowOverride All
     Order allow,deny
     allow from all
</Directory>

6) Save the file and restart the apache.

sudo service apache2 restart

that’s it and now your .htaccess file will work and your laravel application will start working.

Amazon RDS Connection Limit Exhausted

Recently in one of our project we built laravel application and deployed it on Amazon AWS and database was on Amazon RDS. In start there was no issue but after some months we had problems with database connection. After sometime laravel app could not connect to Amazon RDS.

So I checked RDS and dashboard and found out that number of database connection was beyond allowed limits. It means connection open to RDS was not closed after sometime and there were lots of half opened connections. That eventually crashing RDS sever and then connection was not established till we restart the RDS server.

So next step was to check database queries and find the queries which are taking time to execute and get data. After looking into all the queries I got the query which is taking long time to execute and that query was responsible half closed or non closed database connections and which is ultimately crashing Amazon RDS server.

So how I fixed that. Well we have a only one solution to speed up database queries and that is

INDEXING

Yes, that ‘s right indexing solved my issue. There was a table in my database which has 100K records and executing query from it was taking lots of time as there was no indexing. So I created an index on columns which are used mostly for querying that table and after creating index query was working blazing fast.
If you are facing the same issue, better check your database queries and optimize it with indexing to make it faster.

Laravel 5.x Store Uploaded Files to Amazon S3

Recently in one of my Laravel 5.2 project, we used Amazon s3 to store static files and user uploaded files. So here in this blog I am going to explain how to do this.

1) First of all install following plugin through composer.

composer require league/flysystem-aws-s3-v3 ~1.0

2) Now add your S3 credentials to your environment (.env file)

S3_KEY=YOUR_KEY
S3_SECRET=YOUR_SECRET
S3_REGION=YOUR_REGION
S3_BUCKET=YOUR_BUCKET

3) Open config.filesystems.php and configure s3 driver as follow.

‘s3’ => [
            ‘driver’ => ‘s3’,
            ‘key’    => env(‘S3_KEY’),
            ‘secret’ => env(‘S3_SECRET’),
            ‘region’ => env(‘S3_REGION’),y.
            ‘bucket’ => env(‘S3_BUCKET’),
        ]

4) Now open controller where you have code to manage uploaded file and add following dependency.

use IlluminateContractsFilesystemFilesystem;

5) Use following code to store your file to S3.

$image = $request->file(‘user_uploaded_image’);
$imageFileName = time() . ‘.’ . $image->getClientOriginalExtension();
$s3 = Storage::disk(‘s3’);

$filePath = ‘/mypath’/.$imageFileName;
$s3->put($filePath, file_get_contents($image), ‘public’);
$uploadedFileS3Path = ‘https://’.env(‘S3_BUCKET’).’/’.$filePath;
Please note in my case I configured S3 bucket to be direct URL of uploaded file. In case your case if you have not configured it then your path will be as follow.
$uploadedFileS3Path = ‘http://s3-‘.env(‘S3_REGION’).’.amazonaws.com/’.env(‘S3_BUCKET’).’/’.$filePath;
This path you can use to display file and you can store it to database as well.
Special Case 
If you are using it in localhost using XAMPP in your windows system. You have to do following few steps.
Download certificate pem file from this link. https://curl.haxx.se/ca/cacert.pem and store it to some where in your C drive or whatever drive you have your xampp installed.
For example I put it in  C:codecacert.pem
Now open your php.ini file and bottom of the file add following line.
curl.cainfo = C:codecacert.pem
That’s it and it will work in your local environment too. Hope this helps you.