# Connect to MySql

**URL:** <https://forum.serverless.com/t/connect-to-mysql/521>\
**Category:** Serverless Framework\
**Tags:** aws\
**Created:** [October 13, 2016, 10:19am UTC](https://forum.serverless.com/t/connect-to-mysql/521 "2016-10-13T10:19:47Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![frengkys](https://avatars.discourse-cdn.com/v4/letter/f/9fc348/32.png) [@frengkys](https://forum.serverless.com/u/frengkys)\
**Post date:** [October 13, 2016, 10:19am UTC](https://forum.serverless.com/t/connect-to-mysql/521/1 "2016-10-13T10:19:47Z")

</div>

i wonder how to use mysql rds on serverless ?  
ive alreadey npm install mysql and setting up like default but error come out…

const mysql = require(‘mysql’);

let con = mysql.createConnection({  
host : “xxxxx”,  
user : “xxxx”,  
password : “xxxx”,  
database : “xxxx”  
});

con.connect();  
module.exports = con;`

ive already done this… any one know how to setting this up? Or  
is serverless v1 just support dynamoDB and dont support node\_module ?

---

<div class="post-metadata">

**Author:** ![flomotlik](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/flomotlik/32/3_2.png) [@flomotlik](https://forum.serverless.com/u/flomotlik)\
**Post date:** [October 13, 2016, 1:01pm UTC](https://forum.serverless.com/t/connect-to-mysql/521/2 "2016-10-13T13:01:02Z")

</div>

Does that code work on your local system as well? Here is also the guide for it: [http://docs.aws.amazon.com/lambda/latest/dg/vpc-rds.html](http://docs.aws.amazon.com/lambda/latest/dg/vpc-rds.html)

You might need to put the functions into a VPC: [https://serverless.com/framework/docs/providers/aws/vpc/](https://serverless.com/framework/docs/providers/aws/vpc/)

---

<div class="post-metadata">

**Author:** ![frengkys](https://avatars.discourse-cdn.com/v4/letter/f/9fc348/32.png) [@frengkys](https://forum.serverless.com/u/frengkys)\
**Post date:** [October 13, 2016, 2:31pm UTC](https://forum.serverless.com/t/connect-to-mysql/521/3 "2016-10-13T14:31:10Z")

</div>

thanks for reply @flomotlik,😁  
if i am use it on local (without serverless) it work fine…  
so i need vpc to work with RDS ?  
and just add this?

> vpc:  
> securityGroupIds:  
> - securityGroupId1  
> - securityGroupId2  
> subnetIds:  
> - subnetId1  
> - subnetId2

but is serverless v1 not support nodeModule ?

---

<div class="post-metadata">

**Author:** ![flomotlik](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/flomotlik/32/3_2.png) [@flomotlik](https://forum.serverless.com/u/flomotlik)\
**Post date:** [October 13, 2016, 2:53pm UTC](https://forum.serverless.com/t/connect-to-mysql/521/4 "2016-10-13T14:53:13Z")

</div>

If you can connect from your local system into RDS then it should be working from the lambda as well I think. We do support any database or pretty much any service that AWS provides and also node\_modules. Basically if it works in NodeJS it should work in Lambda with Serverless.

---

<div class="post-metadata">

**Author:** ![frengkys](https://avatars.discourse-cdn.com/v4/letter/f/9fc348/32.png) [@frengkys](https://forum.serverless.com/u/frengkys)\
**Post date:** [October 13, 2016, 7:33pm UTC](https://forum.serverless.com/t/connect-to-mysql/521/5 "2016-10-13T19:33:58Z")

</div>

so serverless already support it, so, if i not wanna use vpc… i can still use RDS right ?  
is it something i must include on .yml file to getting node\_module ?

---

<div class="post-metadata">

**Author:** ![buggy](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/buggy/32/177_2.png) [@buggy](https://forum.serverless.com/u/buggy)\
**Post date:** [October 14, 2016, 2:31am UTC](https://forum.serverless.com/t/connect-to-mysql/521/6 "2016-10-14T02:31:10Z")

</div>

@frengkys There are a few of places this could be going wrong. I’d start by making sure you have a working Lambda function that at least attempts to create a connection. `console.log()` and the CloudWatch logs will help you.

Also see [https://aws.amazon.com/blogs/aws/new-access-resources-in-a-vpc-from-your-lambda-functions/](https://aws.amazon.com/blogs/aws/new-access-resources-in-a-vpc-from-your-lambda-functions/) for information on running Lambda functions inside your VPC. You’ll need to do that unless your database port is open to the world (a bad idea)

If you’re still stuck then please post your entire Lambda function here. The code you’ve posted so far won’t run on it’s own.

---

<div class="post-metadata">

**Author:** ![frengkys](https://avatars.discourse-cdn.com/v4/letter/f/9fc348/32.png) [@frengkys](https://forum.serverless.com/u/frengkys)\
**Post date:** [October 14, 2016, 5:31am UTC](https://forum.serverless.com/t/connect-to-mysql/521/7 "2016-10-14T05:31:51Z")

</div>

hiiii, thanks for replying… this is my code

```
'use strict';

const mysql = require('mysql');

let con = mysql.createConnection({
    host : "xxxxxxxxxxxxxxxxxxxx",
    user : "xxxxxxxx",
    password : "xxxxxxx",
    database : "xxxxxxxx",
    });
con.connect();

module.exports.send = function (event, context, callback){

  let data = event.body.json_data;

  const response = {
    statusCode: 200,
    body: JSON.stringify({
      Message: data.hello_world,
    })
  };
  context.succeed(response)
};

```

and the output is {“statusCode”:500,“body”:{“errorMessage”:“Process exited before completing request”}

and .yml is like this

```
functions:
  hello:
    handler: handler.send
    events:
    - http:
       method: POST
       path: send
       integration: lambda
```

---

<div class="post-metadata">

**Author:** ![buggy](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/buggy/32/177_2.png) [@buggy](https://forum.serverless.com/u/buggy)\
**Post date:** [October 14, 2016, 11:25am UTC](https://forum.serverless.com/t/connect-to-mysql/521/8 "2016-10-14T11:25:22Z")

</div>

What does the cloud watch log say? It should contain more information about the error.

---

<div class="post-metadata">

**Author:** ![frengkys](https://avatars.discourse-cdn.com/v4/letter/f/9fc348/32.png) [@frengkys](https://forum.serverless.com/u/frengkys)\
**Post date:** [October 14, 2016, 11:51am UTC](https://forum.serverless.com/t/connect-to-mysql/521/9 "2016-10-14T11:51:17Z")

</div>

sorry, but how can i use cloud watch log on serverless?

---

<div class="post-metadata">

**Author:** ![JakubMatejka](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/jakubmatejka/32/2802_2.png) [@JakubMatejka](https://forum.serverless.com/u/JakubMatejka)\
**Post date:** [October 14, 2016, 12:21pm UTC](https://forum.serverless.com/t/connect-to-mysql/521/10 "2016-10-14T12:21:11Z")

</div>

I guess you should close the connection using `con.destroy();` before calling `context.succeed` but the log in CloudWatch should tell you more. Locate the function in aws console, go to Monitoring tab and follow link “View logs in CloudWatch”

---

<div class="post-metadata">

**Author:** ![frengkys](https://avatars.discourse-cdn.com/v4/letter/f/9fc348/32.png) [@frengkys](https://forum.serverless.com/u/frengkys)\
**Post date:** [October 17, 2016, 8:49am UTC](https://forum.serverless.com/t/connect-to-mysql/521/11 "2016-10-17T08:49:38Z")

</div>

i dont know why but the sql wont connect…  
the error went gone but the sql wont connected  
this is my code now

```
'use strict';

const mysql =require('mysql');

const con = mysql.createConnection({
    host : "xxxxxxxxxxxxxxxxxxxx",
    user : "xxxxxxxx",
    password : "xxxxxxxxxx",
    database : "xxxxxxxxx",
  });

  con.connect(function(err){
        if (err){ throw err
          console.log('-------------------- Error connect to DB --------------------');
          return;
        }
          console.log('-------------------- DB is connected ! ----------------------');
    });

module.exports.send = (event, context, callback) => {
  var data = event.body.json_data;

  console.log("pre");
  con.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
  if (err) throw err;

     console.log('The solution is: ', rows[0].solution);
  });
  console.log("post");

  con.query('SELECT * FROM `temp` ',function (error, results, fields) {
      console.log(results);
    });

  var temp = {name : "frengky"};
  var query = con.query('INSERT INTO `temp` SET ?', temp,function(err,res){
      if(err) throw err ;
    });
  console.log(query.sql);

  con.end();

  const response = {
    statusCode: 200,
    body: JSON.stringify({
      data : data
    }),
  };
  context.succeed(response);
};

```

@buggy @flomotlik @JakubMatejka

---

<div class="post-metadata">

**Author:** ![JakubMatejka](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/jakubmatejka/32/2802_2.png) [@JakubMatejka](https://forum.serverless.com/u/JakubMatejka)\
**Post date:** [October 17, 2016, 9:11am UTC](https://forum.serverless.com/t/connect-to-mysql/521/12 "2016-10-17T09:11:50Z")

</div>

And what do the logs say? BTW. regarding your RDS setup, do you have it publicly accessible?

---

<div class="post-metadata">

**Author:** ![frengkys](https://avatars.discourse-cdn.com/v4/letter/f/9fc348/32.png) [@frengkys](https://forum.serverless.com/u/frengkys)\
**Post date:** [October 17, 2016, 9:14am UTC](https://forum.serverless.com/t/connect-to-mysql/521/13 "2016-10-17T09:14:28Z")

</div>

there is nothing on the logs seriously…

it should be  
’-------------------- Error connect to DB -------------------- or -------------------- DB is connected ! ---------------------- right?  
but none of them shown…

---

<div class="post-metadata">

**Author:** ![frengkys](https://avatars.discourse-cdn.com/v4/letter/f/9fc348/32.png) [@frengkys](https://forum.serverless.com/u/frengkys)\
**Post date:** [October 17, 2016, 9:15am UTC](https://forum.serverless.com/t/connect-to-mysql/521/14 "2016-10-17T09:15:13Z")

</div>

but the ‘pre’ and ‘post’ logs is shown

---

<div class="post-metadata">

**Author:** ![frengkys](https://avatars.discourse-cdn.com/v4/letter/f/9fc348/32.png) [@frengkys](https://forum.serverless.com/u/frengkys)\
**Post date:** [October 17, 2016, 9:36am UTC](https://forum.serverless.com/t/connect-to-mysql/521/15 "2016-10-17T09:36:44Z")

</div>

and publicly accessible is already yes

---

<div class="post-metadata">

**Author:** ![buggy](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/buggy/32/177_2.png) [@buggy](https://forum.serverless.com/u/buggy)\
**Post date:** [October 17, 2016, 9:41am UTC](https://forum.serverless.com/t/connect-to-mysql/521/16 "2016-10-17T09:41:50Z")

</div>

> [@frengkys](#):
>
> it should be  
> '-------------------- Error connect to DB -------------------- or -------------------- DB is connected ! ---------------------- right?

You database connection code is outside of the Lambda function handler. I wouldn’t assume that it’s being run every time the Lambda is called.

Try moving the `const con = mysql.createConnection(...)` and `con.connect(...)` inside the Lambda handler function so that you know it’s actually being run.

---

<div class="post-metadata">

**Author:** ![JakubMatejka](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/jakubmatejka/32/2802_2.png) [@JakubMatejka](https://forum.serverless.com/u/JakubMatejka)\
**Post date:** [October 17, 2016, 9:46am UTC](https://forum.serverless.com/t/connect-to-mysql/521/17 "2016-10-17T09:46:22Z")

</div>

Yes, the container could have been reused which means that the code outside of `module.exports` handler wasn’t run again ([https://aws.amazon.com/blogs/compute/container-reuse-in-lambda/](https://aws.amazon.com/blogs/compute/container-reuse-in-lambda/)).

Second thing is that `console.log` of the error won’t be called at all because you throw the error before, right?

---

<div class="post-metadata">

**Author:** ![frengkys](https://avatars.discourse-cdn.com/v4/letter/f/9fc348/32.png) [@frengkys](https://forum.serverless.com/u/frengkys)\
**Post date:** [October 17, 2016, 9:57am UTC](https://forum.serverless.com/t/connect-to-mysql/521/18 "2016-10-17T09:57:53Z")

</div>

> ‘use strict’;

> module.exports.send = (event, context, callback) =\> {  
> const mysql =require(‘mysql’);

> const con = mysql.createConnection({  
> host : “xxxxxxxxxxxxxxx”,  
> user : “xxxxxxxxx”,  
> password : “xxxxxxxxxxx”,  
> database : “xxxxxxx”,  
> });

> con.connect(function(err){  
> if (err){  
> console.log(‘-------------------- Error connect to DB --------------------’);  
> return;  
> }  
> console.log(‘-------------------- DB is connected ! ----------------------’);  
> });  
> var data = event.body.json\_data;

> console.log(“pre”);  
> con.query(‘SELECT 1 + 1 AS solution’, function(err, rows, fields) {  
> if (err) throw err;

> ```
> console.log('The solution is: ', rows[0].solution);
> 
> ```
> 
> });  
> console.log(“post”);

> var temp = {name : “frengky”};  
> var query = con.query(‘INSERT INTO `temp` SET ?’, temp,function(err,res){  
> if(err) throw err ;  
> });  
> console.log(query.sql);

> con.end();

> const response = {  
> statusCode: 200,  
> body: JSON.stringify({  
> id : data.id,  
> }),  
> };  
> context.succeed(response);  
> };

> module.exports.ping = (event, context, callback) =\> {  
> const response = {  
> statusCode: 200,  
> body: JSON.stringify({  
> message: ‘ping handler called!’,  
> }),  
> };

> context.succeed(response);  
> };

the logs still isnt say anything except ‘pre’ and ‘post’ log… oh and console.log(query.sql)  
but the logs that say Mysql is connected or not isn’t shown…  
@buggy @JakubMatejka

---

<div class="post-metadata">

**Author:** ![frengkys](https://avatars.discourse-cdn.com/v4/letter/f/9fc348/32.png) [@frengkys](https://forum.serverless.com/u/frengkys)\
**Post date:** [October 17, 2016, 10:01am UTC](https://forum.serverless.com/t/connect-to-mysql/521/19 "2016-10-17T10:01:29Z")

</div>

> service: mytest

> provider:  
> name: aws  
> runtime: nodejs4.3

> stage: dev  
> region: ap-southeast-2

> functions:  
> sendData  
> handler: handler.send  
> memorySize: 128  
> timeout: 10  
> events:  
> - http:  
> method: POST  
> path: send  
> integration: lambda  
> cors: true  
> response:  
> headers:  
> Access-Control-Allow-Origin: “\*”

> ping:  
> handler: handler.ping  
> memorySize: 128  
> timeout: 10  
> events:  
> - http:  
> method: GET  
> path: ping

> resources:  
> Resources:  
> AWSLambdaVPCAccessExecutionRole:  
> Type: AWS::IAM::ManagedPolicy  
> Properties:  
> Description: Policy for allowing vpc connection.  
> Roles:
> 
> - {“Ref” : “IamRoleLambdaExecution”}  
> PolicyDocument:  
> Statement:  
> Effect: Allow  
> Action:
> - “dynamodb:\*”
> - “kinesis:\*”
> - “s3:\*”
> - “rds:\*”
> - “ec2:\*”
> - “cloudformation:_"  
> Resource: "_”

---

<div class="post-metadata">

**Author:** ![frengkys](https://avatars.discourse-cdn.com/v4/letter/f/9fc348/32.png) [@frengkys](https://forum.serverless.com/u/frengkys)\
**Post date:** [October 17, 2016, 10:03am UTC](https://forum.serverless.com/t/connect-to-mysql/521/20 "2016-10-17T10:03:47Z")

</div>

or are there something forgotten on my .yml file? @buggy @JakubMatejka @flomotlik

[Next page](https://forum.serverless.com/t/connect-to-mysql/521.md?page=2)
