Question

Unable to connect to Managed Postgres from a Function

I have a managed Postgres database and an App that currently just contains a Function written in Node.

I have added my App and my local IP as trusted sources to my database.

I can query the database from my computer, but the exact same code times out when connecting to the database when running in both the Sandbox and Production Function environments.

This works:

const pool = new Pool({
    connectionTimeoutMillis: parseInt(process.env.PGCONTIMEOUT),
    user: process.env.PGUSER,
    host: process.env.PGHOST,
    database: process.env.PGDATABASE,
    password: process.env.PGPASSWORD,
    port: parseInt(process.env.PGPORT),
    ssl: {
        ca: process.env.CA_CERT
    },
});

let failure = null;

const response = await pool.query('SELECT test_column FROM mrspeaker.mrspeaker.test')
            .catch(reason => failure = reason);
await pool.end();

const actual = failure === null ? response.rows[0].test_column : failure.toString();

expect(actual).toEqual(595);

The exact same code (replacing the assertion with return actual;) running in the function sandbox just returns Error: Connection terminated due to connection timeout.

If I remove all trusted sources from the database I get the same result.

My project.yml:

targetNamespace: ''
parameters: {}
packages:
  - name: mrspeaker
    actions:
      - name: main
        runtime: 'nodejs:default'
      - name: hello
        runtime: 'nodejs:default'
environment:
  BOT_TOKEN: ${BOT_TOKEN}
  PGHOST: ${PGHOST}
  PGPORT: ${PGPORT}
  PGUSER: ${PGUSER}
  PGPASSWORD: ${PGPASSWORD}
  PGDATABASE: ${PGDATABASE}
  PGCONTIMEOUT: ${PGCONTIMEOUT}
  CA_CERT: ${CA_CERT}

My deploy command for the sandbox: doctl sandbox deploy . --env .env

My .env file with values removed:

BOT_TOKEN=

PGHOST=
PGPORT=
PGCONTIMEOUT=
PGDATABASE=
PGUSER=
PGPASSWORD=
CA_CERT=

Am I totally misunderstanding something or am I just missing a small detail? Any help would be greatly appreciated!

Show comments

Submit an answer
Answer a question...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Bobby Iliev
Site Moderator
Site Moderator badge
July 3, 2022

Hi there,

I’ve just tested this and it seems to be working as expected.

Here is also a quick video that shows how to add a Managed Database for your serverless functions:

https://youtu.be/rR4R9tp-4bs?t=150

If you are still seeing that issue even after following the steps, please reach out to our amazing support team who will be more than happy to assist you with your issue! :)

https://www.digitalocean.com/support/

Hope that helps!

- Bobby.