Getting-started-python: "Can't connect to MySQL server on 'localhost' ([Errno 2] No such file or directory)"

Created on 29 Jun 2017  Â·  34Comments  Â·  Source: GoogleCloudPlatform/getting-started-python

This issue has been highlighted twice before, however is still present with the current tutorial and codebase. The application works fine in localhost through the proxy, however deploying to an app engine causes the error.

Error returned: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'localhost' ([Errno 2] No such file or directory)")

This was highlighted #126 and #92 . Both issues are closed, however the stock tutorial is still yielding this error.

I am encountering the same error with the actual application that I would like to deploy (not the tutorial). Both work in localhost mode, and I have tried starting brand new projects, etc.

triage me

Most helpful comment

I had the same error and then I found this log entry in my application logs:

googleapi: Error 403: Access Not Configured. Cloud SQL Administration API has not been used in project [...] before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/sqladmin.googleapis.com/overview?project=[...] then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry., accessNotConfigured

After enabling the Google Cloud SQL API and redeploying the application the SQL connection did work. I don't know if that was a coincidence.

All 34 comments

@andrewsg can you take a look at this?

I've repoened the internal issue tracking this intermittent failure. @mikeklinker129 as the problem appears to come and go, can you please try again and let me know if the problem persists today?

If it does persist, in order to rule out a configuration issue, could you please post or email me your app.yaml and config.py files with the project ID, password and other sensitive information redacted? As an example, see the redacted config.py in this comment: https://github.com/GoogleCloudPlatform/getting-started-python/issues/92#issuecomment-250895875

Thanks @andrewsg -- I think the problem comes and goes... I was able to deploy to another project, however last time I tried to start from scratch and a new project, it kept giving me this error. I will try to set up a new project, and get back to you whether or not I am still seeing the error.

That indeed sounds like the other reports of intermittent issues. Thanks for your report, I'll keep track of the bug internally as well.

I had the same error and then I found this log entry in my application logs:

googleapi: Error 403: Access Not Configured. Cloud SQL Administration API has not been used in project [...] before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/sqladmin.googleapis.com/overview?project=[...] then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry., accessNotConfigured

After enabling the Google Cloud SQL API and redeploying the application the SQL connection did work. I don't know if that was a coincidence.

MySQL its not running on localhost, use

mysql -h ip_address -u user

@larsblumberg Google changed API's name. Now it is named "Google Cloud SQL API". Thank you for information.
After I enabled "Google Cloud SQL API", this error is disappeared.

I have the same issue in the tutorial. (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'localhost' ([Errno 2] No such file or directory)" Connection fails when deployed to AppEngine. The issue though persists. I have tried more than 5 times for 3 days

@JungjaeKimB thanks, I've updated my comment

@ssenchenko did you follow my suggestion above?

@larsblumberg I did try enabling Amin API but it didn’t help. Finally, I managed to get it running on GAE. After I created the Cloud SQL instance in the same region as my App Engine, socket file appeared in place. You guys may check if a region can cause this issue.

@andrewsg I believe you can resolve this issue based on @larsblumberg's suggestion above.

On the Overview page, update 'Before you begin'.1.b to mention enabling _Google Cloud SQL API_, currently only _Google Cloud SQL_ is enabled by default when the project is created. This solved for problem for me, after following all other instructions exactly in the tutorial.

I was facing this issue and what got me out of it was adding to app.yaml:

`

beta_settings:
cloud_sql_instances: :us-central1:,:us-central1:,:us-central1:

`

You can do it for several databases.

I am having the same issue, although I have already enabled the SQL admin API.

@larsblumberg I did try enabling Amin API but it didn’t help. Finally, I managed to get it running on GAE. After I created the Cloud SQL instance in the same region as my App Engine, socket file appeared in place. You guys may check if a region can cause this issue.

Let me check.

@larsblumberg Thank you very much for your post! I was having this SQL connection issue and after extensive troubleshooting I found the issue was caused because the Cloud SQL instance was deployed to region = "west1" and the Cloud App Engine was deployed to region = "west2"

To resolve the issue I just created a new sql database instance and database in the "west2" and updated the "config.py" & "app.yaml" with the updated database information!

Thanks again!

@larsblumberg I did try enabling Amin API but it didn’t help. Finally, I managed to get it running on GAE. After I created the Cloud SQL instance in the same region as my App Engine, socket file appeared in place. You guys may check if a region can cause this issue.

@thomasburling still doenst work getting Can't connect to MySQL server on 'localhost' ([Errno 2] No such file or directory)

Hey folks,

If you are having trouble connecting to Cloud SQL from AppEngine, take a look at the "Connecting from AppEngine" documentation.

Specifically, if you are having issues with 'Can't connect to MySQL server on 'localhost' for GAE-Standard', make sure you are connecting via the unix socket provided at /cloudsql/<INSTANCE_CONNECTION_NAME> (AppEngine Standard doesn't provide a TCP connection option)

FYI to anyone searching, I was seeing this error from not updating my app.yaml, under beta_settings: cloud_sql_instances.

I encountered these errors today. I double checked the following and still continue to encounter the problem:

  1. Updated cloud_sql_instances under beta_settings
  2. Updated APIs to grant permissions

Specifically, following the instructions for python-docs-samples/app-engine/flexible/cloudsql

HI,
Were you able to resolve your issue @altaisukh ?
I am encountering this today, and I am out of my wit - trying to reproduce every steps/instructions.

Thanks!

I could not resolve it in the first project that experienced the symptoms.
Instead, I created a new project and then it worked. I read other people
did this as well.

On Sun, Nov 25, 2018 at 9:46 AM 42force notifications@github.com wrote:

HI,
Were you able to resolve your issue @altaisukh
https://github.com/altaisukh ?
I am encountering this today, and I am out of my wit - trying to reproduce
every steps/instructions.

Thanks!

—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/GoogleCloudPlatform/getting-started-python/issues/129#issuecomment-441427934,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ABbdvQmcHRXvj95S4uWP2GWQr-wRg_52ks5uymcLgaJpZM4OIl5d
.

>

Cheers,

Jess Lampe

I was able to solve my problem. I did not have the Google+ API enabled.
Make sure that you have the Google cloud proxy running and that all of the
APIs that you need are enabled:

Cloud SQL, Cloud Datastore, Cloud Pub/Sub, Cloud Storage JSON, Stackdriver
Logging, and Google+

A guy in office had a similar issue because he forgot to enable a one of
the APIs (Cloud SQL I think) so I would say checking that the APIs are
enabled is a good place to start.

On Sun, Nov 25, 2018 at 2:46 AM 42force notifications@github.com wrote:

HI,
Were you able to resolve your issue @altaisukh
https://github.com/altaisukh ?
I am encountering this today, and I am out of my wit - trying to reproduce
every steps/instructions.

Thanks!

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/GoogleCloudPlatform/getting-started-python/issues/129#issuecomment-441427934,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AkWtFJInR2BJdJmoHeDLeTtN3HSPO5-wks5uymcLgaJpZM4OIl5d
.

Is it solved? I still experience this error though I did try above solutions. Enable APIs, delete localhost, creating a new database with the same region, etc. I

Hey folks,

Just to reiterate, this is a common issue caused when users miss a step in the instructions. I encourage you to take a look at the "Connect from App Engine page" and make sure to note the differences between Standard/Flexible runtimes:

  1. Standard runtimes provide a unix socket at /cloudsql/<INSTANCE_CONNECTION_NAME>. This uses the App Engine standard service account to authenticate to the project the Cloud SQL instance is in, so make sure it has the correct permissions.

  2. Flexible run-times require an update to the app.yaml, and support both TCP and Unix Sockets. There is an example here.

You need to check the scripts on your settings.py

Kind Regards,

On 10/01/2019, at 00:27, Vo Truong Vinh notifications@github.com wrote:

Is it solved? I still experience this error though I did try above solutions. Enable APIs, delete localhost, creating a new database with the same region, etc. I

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub, or mute the thread.

Hmm, I encountered the same error when I first deployed. My app.yaml and config.py files were in order. However, I _did_ notice the following things:

  • I hadn't enabled the Cloud SQL Admin API (something that was mentioned above, and from looking at the logs it seemed that API needed to be enabled, even though it's not listed in the tutorial)
  • When I deployed, my local Python Virtual Environment was not activated (I'm not sure if this would make a difference though)

So I first activated the Cloud SQL Admin API, and tried accessing the application again from the cloud url. It returned the same error.

Then, I activated my Python Virtual Environment with all the dependencies, and redeployed using the gcloud app deploy command, while my virtual environment was activated. When I tried accessing the app from the cloud this time, it worked.

So it seems hard to tell what made it work. Maybe I just had to enable the Cloud SQL Admin API (but then again, when I enabled it without redeploying, it didn't work). Maybe I was supposed to have my Python Virtual Environment activated during deployment (I'm still a beginner at using GCP, so I'm not sure how it handles dependencies and libraries, so I'm not really sure if this would make a difference). Or maybe it just wasn't working for some unknown reason, and redeploying just did the trick.

For my testing: 1) Cloud SQL Admin API must be enabled 2) The App Engine and SQL Instance must be in the same Region.

Enable Cloud SQL Admin API (not just Cloud SQL) and redeploy - not necessary to deploy from virtuel env.
Sql proxy doesn't have to be running - as you would expect that is just for local connection

Hey folks,

Just to reiterate, this is a common issue caused when users miss a step in the instructions. I encourage you to take a look at the "Connect from App Engine page" and make sure to note the differences between Standard/Flexible runtimes:

  1. Standard runtimes provide a unix socket at /cloudsql/<INSTANCE_CONNECTION_NAME>. This uses the App Engine standard service account to authenticate to the project the Cloud SQL instance is in, so make sure it has the correct permissions.
  2. Flexible run-times require an update to the app.yaml, and support both TCP and Unix Sockets. There is an example here.

@kurtisvg

Thanks for pointing this out. Would you mind clarifying something further?

In a standard python environment I use the following to connect to the db:

conn = pymysql.connect(user=os.environ['DB_USER'],
                           password=os.environ['DB_PASS'],
                           unix_socket='/cloudsql/{}'.format(os.environ['DB_CONN']),
                           db=os.environ['DB_NAME'],
                           cursorclass=pymysql.cursors.DictCursor,
                           autocommit=True)

after setting environment variables using configs.

In the flex environment, I understand that I need to add something like:

beta_settings:
  cloud_sql_instances: <INSTANCE_CONNECTION_NAME>

What's confusing me is, what exactly is the relationship between and how I'm constructing the socket path above? Would I substitute whatever I have stored in DB_CONN (cf above python code) for (cf above app.yaml beta_settings ...)?

@tc64 - This example here shows how to pass the INSTANCE_CONNECTION_NAME in as an environment variable and use it in the unix_socket path.

I'm having this same issue. It WAS working a couple days ago, and then stopped and I've been pulling my hair out trying to figure it out... only to realize: OperationalError(2003, "Can't connect to MySQL server on 'localhost' ([Errno 2] No such file or directory)"))" UGH. Definitely not closed.

I experienced this issue when running a flask app locally against a remote CloudSQL db instance (using cloud_sql_proxy). My SQLALCHEMY_DATABASE_URI Connection looked like:

mysql+pymysql://{<user-name}:{<user-password>}@{<db-hostname>}/{<database-name>}?unix_socket=/cloudsql/{<connection-name>}

Turns out connections to CloudSQL can only use either TCP or unix socket, not both. Apparently the proxy uses TCP connection

Solution: remove "unix_socket" param when running locally against the live URI so it looks like this:

mysql+pymysql://{<user-name}:{<user-password>}@{<db-hostname>}/{<database-name>}

@kiptoomm To clarify, you can use either a TCP socket or a Unix socket using the proxy. Your mistake was trying to pass both arguments to the mysql driver at the same, which caused the driver to fail.

Was this page helpful?
0 / 5 - 0 ratings