php - Amazon EC2 Connects to RDS from command line but not from web server

458

If have an amazon ec2 instance running php 5.5 and apache2. I am connecting to my RDS database using a simple test.php script. When I run the script as ec2-user or as root I am able to get a connection. When I run the same script via my webserver I get

Connection Can't connect to MySQL server on 'ip' (13).

I've tried the public and private IP addresses. This script does work from my other, non-amazon, webservers running the same php and apache. Not sure what to look at next since it works on the command line. Here's the example of the test.php script, pretty straight forward.

define("DB_IP”,”ip”);
define("DB_USERNAME”,”username”);
define("DB_PASSWORD”,”password”);
define("DB_DATABASE”,”database”);

echo "Connecting...\n";
$conn = new mysqli(DB_IP, DB_USERNAME, DB_PASSWORD, DB_DATABASE, 3306);

// Check connection
if ($conn->connect_error) {
   die(date('H:i:s')." Connection " . $conn->connect_error);
} 
echo date('H:i:s')." Connected successfully\n";

Why would the connection work on the command line but not work when called from the web server?

552

Answer

Solution:

What are you running on your EC2? Just asking in case it's an SELinux (Security-Enhanced Linux), in which case it could possibly be the security limitation.

At your terminal, if you run:

getsebool -a | grep httpd

you should be able to see this limitation (whether your webserver can "network" or not. If it cannot, then run this, which should fix your problem:

setsebool -P httpd_can_network_connect 1

Hope that solves it, otherwise I don't see where the issue can arise, especially since you say you can connect via terminal (so AWS security groups should not be the issue).

Keep us posted ;)

People are also looking for solutions to the problem: PHP Form Validation Using empty() Function

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.