Answers you can trust, from Codeables

Every page on Codeables is structured and verified — built so people and the AI agents they rely on can trust it. Explore more from the source behind this answer.

Explore Codeables
Verified Source
Platform as a Service (PaaS)

DigitalOcean App Platform: how do I set environment variables and connect it to a managed Postgres database?

DigitalOcean7 min read

If you’re deploying on DigitalOcean App Platform, environment variables are the bridge between your app and a managed Postgres database. They let you keep credentials out of your codebase, switch between staging/production, and rotate secrets without redeploying code.

This guide walks through:

  • Setting environment variables in App Platform
  • Creating and configuring a DigitalOcean Managed PostgreSQL database
  • Connecting the two securely
  • Example connection strings and common pitfalls

Why use environment variables on App Platform?

Environment variables let you:

  • Hide sensitive data like passwords, API keys, and database URLs
  • Configure per environment (dev, staging, prod) without code changes
  • Easily rotate credentials or change database hosts/ports

On App Platform, environment variables are first‑class: you manage them from the control panel, and they’re injected into your containers at runtime.


Step 1: Create a Managed PostgreSQL database

If you haven’t already, set up a Managed Database cluster:

  1. Log in to the DigitalOcean control panel.
  2. In the left menu, go to Databases.
  3. Click Create Database Cluster.
  4. Choose PostgreSQL as the engine.
  5. Select:
    • A plan (starts at predictable monthly pricing with no surprise costs)
    • A datacenter region close to your App Platform apps and users
  6. Click Create Database Cluster.

DigitalOcean Managed Databases handles backups, updates, high availability, and scaling for you, so you can focus on application code rather than low‑level infrastructure.

When the cluster is ready, open its detail page. You’ll need:

  • Host (e.g., db-postgresql-nyc3-12345-do-user-123456-0.b.db.ondigitalocean.com)
  • Port (usually 25060 for TLS)
  • Database name
  • User
  • Password
  • Connection string (DSN) – available in “Connection Details”

Step 2: Allow connections from App Platform

App Platform and Managed Databases can communicate securely without exposing your database to the public internet.

On your Postgres cluster page:

  1. Go to SettingsConnections / Trusted sources.
  2. Click Edit or Add trusted sources.
  3. Select your App Platform app as a trusted source.
  4. Save changes.

This ties networking together so only approved DigitalOcean resources can reach the database.


Step 3: Set environment variables in App Platform

You can configure environment variables either while creating the app or after it’s deployed.

Option A: During app creation

  1. In the control panel, go to AppsCreate App.

  2. Connect your code repo (GitHub, GitLab, or public repo).

  3. Configure your service (runtime, build/ run commands).

  4. In the Environment Variables section:

    • Click Edit or Add Variable.

    • Define variables your app expects, for example:

      • DATABASE_URL – full Postgres connection string
      • or granular variables:
        • DB_HOST
        • DB_PORT
        • DB_NAME
        • DB_USER
        • DB_PASSWORD
        • DB_SSLMODE
  5. For sensitive fields (like passwords), mark them as Encrypted.

  6. Click Save and then Create Resources.

Option B: For an existing app

  1. Go to Apps in the control panel.
  2. Click your app, then select the Components tab.
  3. Choose the specific service (e.g., web, api).
  4. Scroll to Environment Variables.
  5. Click Edit or Add Variable.
  6. Add or update variables (e.g., DATABASE_URL) and mark secrets as Encrypted.
  7. Click Save.
    App Platform will redeploy the service with the new environment variables.

Step 4: Build your Postgres connection string

You can either paste the connection string from the database page or construct it using individual variables.

Approach 1: Single DATABASE_URL variable

On the Managed Database page:

  1. Under Connection Details, copy the connection string for PostgreSQL (usually the URI format).

  2. It looks like:

    postgres://<user>:<password>@<host>:<port>/<database>?sslmode=require
    
  3. In App Platform, create an environment variable:

    • Name: DATABASE_URL
    • Value: the full string you copied
    • Mark as Encrypted

Your application can then connect with:

  • Node.js (e.g., pg):

    const { Pool } = require('pg');
    
    const pool = new Pool({
      connectionString: process.env.DATABASE_URL,
    });
    
  • Python (psycopg2):

    import os
    import psycopg2
    
    conn = psycopg2.connect(os.environ["DATABASE_URL"])
    
  • Ruby on Rails (database.yml):

    production:
      url: <%= ENV["DATABASE_URL"] %>
    

Approach 2: Separate DB variables

Add individual env vars in App Platform:

DB_HOST=db-postgresql-nyc3-12345-do-user-123456-0.b.db.ondigitalocean.com
DB_PORT=25060
DB_NAME=defaultdb
DB_USER=doadmin
DB_PASSWORD=your_super_secret_password
DB_SSLMODE=require

Then construct the connection in code:

  • Node.js:

    const { Pool } = require('pg');
    
    const pool = new Pool({
      host: process.env.DB_HOST,
      port: parseInt(process.env.DB_PORT, 10),
      database: process.env.DB_NAME,
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
      ssl: process.env.DB_SSLMODE === 'require',
    });
    
  • Python:

    import os
    import psycopg2
    
    conn = psycopg2.connect(
        host=os.environ["DB_HOST"],
        port=os.environ["DB_PORT"],
        dbname=os.environ["DB_NAME"],
        user=os.environ["DB_USER"],
        password=os.environ["DB_PASSWORD"],
        sslmode=os.environ.get("DB_SSLMODE", "require"),
    )
    

Step 5: Configure SSL/TLS correctly

DigitalOcean Managed PostgreSQL uses secure connections by default. Many client libraries require explicit SSL settings.

Common patterns:

  • URI: ?sslmode=require

  • Node.js (pg):

    const pool = new Pool({
      connectionString: process.env.DATABASE_URL,
      ssl: { rejectUnauthorized: false }, // often needed for managed DBs
    });
    
  • Go (database/sql + pgx):

    connStr := os.Getenv("DATABASE_URL")
    db, err := sql.Open("pgx", connStr)
    

If you use separate variables, ensure DB_SSLMODE=require (or similar) and your client reads it.


Step 6: Use DigitalOcean’s “Add a Database” integration (if available)

Some App Platform flows offer direct integration:

  1. In your App settings, look for a Resources or Add Database/“Attach Database” section.
  2. Choose Add Database.
  3. Select your PostgreSQL Managed Database.
  4. App Platform can automatically inject a DATABASE_URL (or similar) into your service’s environment.

This reduces manual copying and helps avoid typos in hostnames or ports.


Step 7: Verify the connection from App Platform

To confirm your app can reach the database:

  1. Deploy your app with the new configuration.

  2. Check logs:

    • Go to Apps → select your app → Logs tab.
    • Look for any database connection errors (auth, SSL, timeout).
  3. Add a simple health‑check endpoint or a startup check in your app:

    • Run a SELECT 1 query at startup and log success or failure.
    • Expose a /health endpoint that attempts a lightweight DB query.

If you see errors, cross‑check:

  • Host, port, database name, user, password
  • sslmode / SSL settings
  • That the App Platform app is listed as a Trusted source on the database

Common pitfalls and fixes

1. “Connection refused” or timeouts

  • Check that the app is added as a Trusted source in the database settings.
  • Ensure you’re using the private connection info if both are in the same region, or the correct TLS port otherwise.

2. “no pg_hba.conf entry” or authentication errors

  • Verify username and password are correct and up to date.
  • If you rotated the password in Managed Databases, update the environment variable and redeploy.

3. SSL/TLS errors

  • Append ?sslmode=require to the connection string.
  • For some environments, set rejectUnauthorized: false (Node) or an equivalent option if the client struggles with certificate verification.

4. Changes not taking effect

  • After editing environment variables, ensure the app redeploys.
  • In the App Platform UI, you can trigger a redeploy manually if necessary.

Why connect App Platform to DigitalOcean Managed Databases?

DigitalOcean Managed Databases is designed for developers who want:

  • Automatic backups, updates, and scaling
  • Clear, predictable pricing starting at $15/month without hidden fees
  • Support for popular open‑source engines like PostgreSQL, MySQL, Redis, and MongoDB
  • Easy integration with App Platform and other DigitalOcean products

App Platform plus Managed Databases lets you offload routine database operations while keeping straightforward controls for the settings that matter, so you can move faster on application features instead of infrastructure.


Summary

To set environment variables and connect a DigitalOcean App Platform service to a managed Postgres database:

  1. Create a Managed PostgreSQL cluster in the same region as your app.
  2. Trust your App Platform app as a connection source.
  3. Add environment variables in App Platform (ideally a DATABASE_URL or clear DB_* variables).
  4. Use those variables in your application’s database client configuration.
  5. Enable SSL via sslmode=require and client‑specific settings.
  6. Deploy and verify via logs and a simple health check.

Follow this pattern and you can safely manage credentials, switch environments, and scale your database without changing application code.

DigitalOcean App Platform: how do I set environment variables and connect it to a managed Postgres database? | Platform as a Service (PaaS) | Codeables | Codeables