Error Establishing Database Connection AWS Elastic Beanstalk with RDS - php

I am trying to set up a simple Wordpress site using AWS Elastic Beanstalk with a disconnected RDS database (not part of the ELB instance in case I want to connect multiple sites to the DB) by roughly following this guide:
https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/php-hawordpress-tutorial.html.
However, I am getting the following error when loading up the Wordpress install:
Error establishing a database connection
So far I have tried to troubleshoot the issue by:
Verifying that both the RDS and EC2 are on the same VPC with the same security group attached which has the proper inbound rules:
I have verified that the RDS is available like so:
nrb$ nc -zv <***masked-connection-string***> 3306
found 0 associations
found 1 connections:
1: flags=82<CONNECTED,PREFERRED>
outif en0
src 192.168.20.149 port 58825
dst 3.215.127.182 port 3306
rank info not available
TCP aux info available
Connection to <***masked-connection-string***> port 3306 [tcp/mysql] succeeded!
I have verified that my EC2 can connect to the RDS by SSHing into it and using the mysql command and copy/pasting my env variables to make sure there were no typos as recommended by #littleforest, which successfully connected to the database.
I have updated the sample PHP application that comes with AWS to output my env variables to make sure that the server is reading them. They outputted as they should.
My wp_config.php file looks like as recommeneded by the turtorial:
<?php
define('DB_NAME', $_SERVER['RDS_DB_NAME']);
define('DB_USER', $_SERVER['RDS_USERNAME']);
define('DB_PASSWORD', $_SERVER['RDS_PASSWORD']);
define('DB_HOST', $_SERVER['RDS_HOSTNAME'] . ':' . $_SERVER['RDS_PORT']);
define('DB_CHARSET', 'utf8');
define('DB_COLLATE', '');
define('AUTH_KEY', $_SERVER['AUTH_KEY']);
define('SECURE_AUTH_KEY', $_SERVER['SECURE_AUTH_KEY']);
define('LOGGED_IN_KEY', $_SERVER['LOGGED_IN_KEY']);
define('NONCE_KEY', $_SERVER['NONCE_KEY']);
define('AUTH_SALT', $_SERVER['AUTH_SALT']);
define('SECURE_AUTH_SALT', $_SERVER['SECURE_AUTH_SALT']);
define('LOGGED_IN_SALT', $_SERVER['LOGGED_IN_SALT']);
define('NONCE_SALT', $_SERVER['NONCE_SALT']);
$table_prefix = 'wp_';
define('WP_DEBUG', false);
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
require_once(ABSPATH . 'wp-settings.php');
And in the config > software of my Elastic Beanstalk, I have verified these variables:
RDS_DB_NAME
RDS_HOSTNAME
RDS_PASSWORD
RDS_PORT
RDS_USERNAME
I know there is something stupid that I am missing which an AWS guru is going to catch right away, but this is driving me nuts.

Alright! After a few migraines and screaming at my keyboard, I have figured out what was going on.
Since I was able to connect to the RDS server via SSH, I assumed that the problem had to be with Wordpress. Sure enough, when I turned on DEBUG mode, Wordpress could not find my database on the RDS server.
It turns out when you set up an RDS the DB instance ID is not the DB name. However, even when specifying a name under the advanced config options, RDS never setup that DB on launch.
So to solve this problem, I had to:
SSH into my EC2 Instance and connect to RDS using the mysql command as #littleforest suggested
Create the database inside the mysql console.
Then once I verified the DB existed in the mysql console, I was able to run the famous 5 minute Wordpress installation.

Related

Error connecting a remote server from a PHP page

I have a .php file which should receive and show data from a remote database. I run my program from PHPStorm (which is connected to the remote database through the "Database" right-hand pane) and a browser. Both ways I get an error which depends on the number of arguments I pass to pg_connect() function.
If I use
$dbconn = pg_connect("host=pg hostaddr=server.address.ru port=5432 dbname=studs user=... password=...")
than the error is
Unable to connect to PostgreSQL server: could not parse network address "server.address.ru": Unknown host in...
But I am sure that I wrote the address correctly (there are no typos in it). This way I am not sure about the correctness of the format of the passed arguments.
If I use
$dbconn = pg_connect("host=server.address.ru dbname=studs user=... password=...")
command, the error is
pg_connect(): Unable to connect to PostgreSQL server: could not connect to server: Connection timed out
I found a lot of information about this errors, but it mostly refers to localhosts and doesn't solve my problem. I guess, the problem can be in the way this connection is set in the function, but I do not know why it doesn't work properly. How can I solve it?
Thanks to #TangentiallyPerpendicular, I got on a right way of setting the connection. But since I have PostgreSQL remote connection, it wasn't just up to this answer.
What I did and how I set the connection (I work from PHPStorm so all the actions are based on this platform):
Open PuTTY and set an SSH connection (an SSH tunnel) between the server's DB port (for PostgreSQL it's usually 5432) and your local computer's PostgreSQL port (5432 most often too). You can do the same from a command line.
Open PHPStorm and in "Database" section (an icon on the right-hand side of the environment or "Data Sources and Drivers" in Settings) set general information ("General" section) and set another SSH tunnel ("SSH/SSL"). In SSH Configurations (the same "SSH/SSL" section) set a local port - it will be important in our connection! Let's say, this port is 20000. The port of the server you're connecting to is a usual one (usually 22 or 2222).
In the program the right use of function is $dbconn = pg_connect("host=localhost port=20000 dbname=studs user=... password=...") or die('Error: ' . pg_last_error());
The connection is set.
For those who has troubles setting an SSH tunnel with a remote PostgreSQL from PHP this can be useful too.

Unable to Connect to mysql db through php in GCE instance with ubuntu

I'm a little bit frustrated with a problem I'm having in a system migration from AWS to GCE.
I've an ec-2 instance running on amazon web services, perfectly working and configured.
The problem is that google is offering a 100.000$ credit in a special plan for Startups, my company's CEO asks for a migration, so here I am.
I have all running and almost fully configured in a ubuntu 14.04 LTS instance, I said almost, because I can't achieve a simple task such as connect to a Mysql db :(, and I think I'm missing something in someplace and my mind gets offuscated, so I need your help.
First of all, I only having this problem on remote server, I've tested it like a hundred times in local, and of course in aws, where it is currently in production state, so I have no clue what or where exactly the problem is.
My GCE config:
OS: Ubuntu 14.04 LTS
HHD: 30GB persistence ssd disk
CPU : 2x
RAM : 7,5 GB
Zone: europe-west1-c
Static Ip
So, I installed Lamp and phpmyadmin, all works like a charm. I disable root access from remote clients to Mysql db, configured php and apache modules.
The Web app is a Rest Api, based on PHP(Slim), that, like I just said, is now working on AWS.
When I call to and endpoint that doesn't need to retrieve any data from the db, it works well, the problem comes when the endpoint called try to access the db. In that case the request never respond, it keeps loading forever until I abort the request. It is kind of weird, because I can manipulate all the data through phpmyadmin, which access to the db the same way mysqli does.
If I checked the logs, nothing is printed on them. Only when I change the "locahost" host param, it prints a log saying: "No mysql db on XXX.XXX.XXX.XXX"(IP).
config.php File
define('DB_USERNAME', 'user');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'localhost');
define('DB_NAME', 'db_name');
DbConnect.php
function connect() {
include_once dirname(__FILE__) . '/Config.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
/* change character set to utf8 */
if (!$this->conn->set_charset("utf8")) {
echo "Error loading character set utf8: " . $this->conn->error;
}
// returing connection resource
return $this->conn;
}
loops forever img
Expected Response img
Any help is welcome!
Have you changed the bind-address parameter in the my.cnf MySQL config file? This has caught me a few times. MySQL by default in Ubuntu 14.04 will only listen on localhost and will ignore remote connections.
Also, check out the answer to this question and it might give you some help as well: Remote Connections Mysql Ubuntu - bind address failed

Amazon AWS database connection error with valid settings

I'm running both a wordpress site as well as a mediawiki off of the same web servers. The mediawiki site works great! The wordpress site, meh. Not so much. I keep getting the common database connection error:
Error establishing a database connection
And as far as I can tell the settings between the mediawiki site and the wordpress site are nearly identical.
Here's the media wiki config first since that one's working:
## Database settings
$wgLBFactoryConf['class'] = 'LBFactorySimple';
$wgDBtype = "mysql";
$wgDBservers = '';
$wgDBserver = "db.example.com";
$wgDBssl = true;
$wgDBname = "jfwiki";
$wgDBuser = "admin_ssl";
$wgDBpassword = "secret";
And here's what the wordpress database connection settings look like since they are not:
/** MySQL database username */
define('DB_NAME', 'jokefire');
define('DB_USER', 'admin_ssl');
/** MySQL database password */
define('DB_PASSWORD', 'secret');
/** MySQL hostname */
define('DB_HOST', 'db.example.com');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
/** Contact the database over a secure connection */
define('DB_SSL', true);
I realize that they're not exactly the same. But I think you can make an easy correlation between the mediawiki settings and the settings for wordpress. And they look similar enough to think that wordpress should be working. Right?
The only real other difference is the name of the database each site is using, which I guess makes sense.
But the fact that medawiki works fine tells me that the user and password set for both sites has access to the database.
Just for laughs I use the account settings from the wordpress config to demonstrate that I can connect to the DB on the command line. Again, it's the same account info that I have in the wik site:
#mysql -uadmin_ssl -p -h db.example.com -D jokefire -e "show tables" | head -5
Enter password:
Tables_in_jokefire
wp_bp_activity
wp_bp_activity_meta
wp_bp_chat_channel_users
wp_bp_chat_channels
Also, I created a basic php script to see if it could connect to the database
<?php
$link = mysql_connect('db.example.com', 'admin_ssl', 'secret');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
And to my surprise it can't connect!
php testconnect.php
Could not connect: Access denied for user 'admin_ssl'#'ec2-54-86-143-49.compute-1.amazonaws.com' (using password: YES)
Why am I surprised that it can't? Because again 1) the wiki can connect to the database no problem. And 2) I can connect to the db on the command line using the same credentials.
My API MySQL Client version is:
Client API version mysqlnd 5.0.10 - 20111026 - $Id: c85105d7c6f7d70d609bb4c000257868a40840ab $
Hope this helps narrow down the problem. Thanks!
The host name could easily be the issue.
Try select user,host from mysql.user where user='admin_ssl' order by host;
As is often the case on AWS servers, what works on localhost or 127.0.0.1 as a host is quite different than a host coming in from elsewhere.
From your PHP sample, the mysql server cannot authenticate the user and host. My bet it is the ec2-54-86-143-49.compute-1.amazonaws.com part of it.
A quick test would be to go on a mysql prompt on the server in question, and perform a create user and grant for such a user. Other people would recommend creating a 'admin_ssl'#'%' user so it works regardless of hostname coming in. I would be careful with that approach.
In order to lock down security, I am willing to create a user on AWS such as create user 'dbAdmin'#'mc83.newyork.comcastbusiness.com' IDENTIFIED BY ... to ensure I don't user wildcards like '%'.
Don't forget the grants. But that is getting ahead of the issue at hand, which is a connect.
good luck.

Connect to Amazon RDS with PHP

I am trying to connect my RDS Instance with my PHP connection file.
This is what I have in my file:
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'User Name');
define('DB_PASSWORD', 'Password');
define('DB_DATABASE', 'DATABASE');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
I replaced localhost with my endpoint (rds thing) url, username and password with my RDS Instance user and pass and database name the one I've set when I created the instance. But it doesn't seem to work.
Is there anything else I have to do that I am not aware of or should it work?
RDS instances do not have a static IP address attached to them, you always use the endpoint for the host. For example:
database1.jlsdfjhgsdf.us-east-1.rds.amazonaws.com
If you are connecting to the instance with a username other than the root database account, you will need to grant the user privileges.
Check security group settings. If you are connecting from another EC2 instance on Amazon you will need to attach that security group. If you are trying to connect from outside AWS, you will need to whitelist the IP address you are accessing from.
Some ideas:
Try using the actual IP of the instance, then it should work.
Did you authorized access to your DB instance?
You may want to have a look at Get Started with Amazon RDS to properly setup your RDS instance
I was facing a similar issue whilst trying to connect an EC2 Apache server using PHP to the RDS MySQL instance.
Weirdly I could establish a connection via CLI - once in mysql running status will tell you which user youre logged in with, plus the port, server name etc.
Turned out some AMI images have SELinux enforcement - meaning the apache server cant send network requests as pointed out by this gentlemen (http://www.filonov.com/2009/08/07/sqlstatehy000-2003-cant-connect-to-mysql-server-on-xxx-xxx-xxx-xxx-13/)
Other points:
Make sure inbound ports are set for your RDS DB
In MySQL make sure the host is set to '%' as opposed to localhost
Always use the endpoint string to connect as the RDS IP changes
I was recently having a lot of trouble with this also but was able to fix it. I made sure my security groups (for the RDS and for EC2) were allowing each other. I was able to run my script from the terminal and connect to my database also from the terminal, but I couldn't get the script to run/connect to MySQL from a browser. It turns out I did not have mysql-server installed-- once I installed that and restarted httpd and mysqld it worked like a charm.
This article is what led me to installing mysql-server and the service starts/restarts. Hope it helps! -- http://www.rndmr.com/amazon-aws-ec2-easy-web-serverset-up-guide-with-a-mac-and-coda-2-256/
Just accepts all incoming connections.
I also had the connection problem between the ec2 (apache + php server) and the RDS (Mysql server) when following the tutorial at http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Tutorials.WebServerDB.CreateDBInstance.html.
I solved it by using the double quote when specifying the connection value while the guideline is using single quote.
define('DB_SERVER', "localhost");
define('DB_USERNAME', "User Name");
define('DB_PASSWORD', "Password");
define('DB_DATABASE', "DATABASE");
I was trying to connect to my DB instance using node-mysql. I found that I the endpoint that RDS provided me with did a DNS lookup. Followed that up and changed the URL to that one. I was only able to connect with mysql via command line until then. When I changed it to the resulting endpoint after the lookup, node-mysql was finally able to connect.

Unknown MySQL server host

When trying to connect to my database server, i encounter the problem of unknown host:
Warning: mysqli::mysqli() [mysqli.mysqli]: (HY000/2005): Unknown MySQL server host 'xxxxxxxxxxxxx:port' in index.php on line 18
the line 18 is that line where i try to request to connection the the MySQL server:
$this->db = new mysqli($db_host, $db_user, $db_psw, $db_name);
I host my database on the 1&1 website hosting company.
This is usually the case when name resolving doesn't work on the host. If your connect destination is always the same, you might want to use its IP address for connecting instead.
If you use this code:
$Mysqli= new mysqli('mysql2.servidoreswindows.net:3306',
'usu', 'pass', 'dbname');
you can try to write host without port
That is:
$Mysqli= new mysqli('mysql2.servidoreswindows.net', 'usu', 'pass', 'dbname');
Please pay attention with AWS security groups:
In my case I can connect to RDS from my computer through Telnet and
I can connect through Mysql Workbench also but I cant connect from
my EC2 instance that is within the same VPC as the RDS.
The solution was:
I have created a security group (exampl1) for RDS and assigned to it.
I have created a security group (exampl2) for EC2 and assigned to it.
and I have assigned the RDS security group (exampl1) to the EC2 too. << this saves me.
Info: If your EC2 has assigned 2 or more security groups, then in the RDS security group inbound source has to create rules as many security groups has your EC2 assigned.
Amazon docs says:
The EC2 instance in the VPC shares the same VPC security group with the DB instance.
http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.RDSSecurityGroups.html
I know this is an old question. But I ran into this same issue today, and none of the answers I found were the right one.
The issue in my case ended up being that port 3306 is not open on our firewall, and I was attempting to connect to an internal mysql database from an external server.
I'm not sure why the error it gives you is "Unknown Host" in this case. I would have expected something more like "Unable to connect." or "Connection refused.", but using the exact same code from an internal server worked fine, leading me to this conclusion.
Make sure you're not including the "http://" part. I was using http://example.com in my .env file. When I left it as example.com it worked.

Categories