Search code examples
phpmysqlamazon-web-servicesconnectioninternal

Connecting From PHP Server to MySQL Server on Amazon AWS


I have two servers setup on Amazon AWS. One server is running PHP and the other has MySQL. I can connect to the MySQL database through my terminal and MySQL Query Browser.

I am trying to get a connection between the PHP and MySQL servers.

Here is the PHP Code that I am using (works for "localhost" databases)

$dbbase = 'mydb';               
$dbuser = 'myuser';         // Your MySQL username
$dbpass = 'mypassword';     // ...and password
$dbhost = 'localhost:3306';  // Internal IP for MYSQL Server

// connect to database
$dblink = mysql_connect($dbhost, $dbuser, $dbpass) 
    or die ("System Down");

mysql_select_db($dbbase, $dblink) 
    or die ("Database Down");

It is my understanding that I should be able to route this an internal AWS traffic, but at this point I will take anything that works and build from there.

Here is what I have done:

  • Added the ip of the PHP server to the Security Group for MySQL(3306) permissions

  • Tried to use the internal, external, and private IPs/DNSs of the MySQL Server as the $dbhost variable

  • Created myuser@% (wildcard) on thy MySQL server

Any ideas or tips would be much appreciated.


Solution

  • I've got this working.

    I think the big trick was to add this rule to the Security Group:

    Type: MySQL

    Source: 10.0.0.0/8

    My understanding is that 10.0.0.0/8 covers all internal amazon IPs. I think you could tighten this up, but it is possible for the internal IP of your servers to change, so that would need to be managed.

    Then in my PHP script I used the Private DNS of my MySQL Server. It should look something like this: ip-10-10-100-100.ec2.internal:3306

    In the end, I think that is everything that I did.