Occasionally getting error "Could not connect to server: Connection refused"
We are occasionally getting the connection refused error in production. We get this error 2-3 times a day. Our app is deployed in App Engine. I couldn't find anything helpful in the logs. We are using psycopg2 v 2.8.5 binary as postgresql engine.
could not connect to server: Connection refused Is the server running locally and accepting connections on Unix domain socket "/cloudsql/xxxxxxxx:us-central1:xxxxx-production-1/.s.PGSQL.5432"?
Are you using connection pooling as part of your setup? Mind sharing the application code that shows how you're creating connections?
No. We aren't using connection pools. We are using Django framework.
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'options': '-c search_path="schemaname"' }, 'NAME': 'dbname', 'USER': 'username', 'PASSWORD': 'xxxxxxx', 'HOST': f'/cloudsql/xxxxxxxx:us-central1:xxxx-production-1', 'PORT': '5432', } }
Hi @Tech2pr,
Opening and closing connections can have some additional overhead, your application may be experiencing the error when it is seeing higher database traffic, hitting Django's limit for number of connections.
One thing you can try is setting the CONN_MAX_AGE param in your config. This will allow persistent database connections (similar to connection pooling) so that connections can be re-used. This might help reduce the burden of opening and closing each connection since the default for CONN_MAX_AGE is 0.
Example:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'CONN_MAX_AGE': 60,
'OPTIONS': {
'options': '-c search_path="schemaname"'
},
# ...
Let me know if the above helps at all, thanks for raising this question!
Have a great day.
Thank you @jackwotherspoon. We have implemented the suggestion and we will monitor for the same error in the upcoming days.
How's the updated deployment looking @Tech2pr?
I’m going to close this since it’s been awhile now. Feel free to add additional info here and re-open if necessary.