Secure database connection strings

Topic: Databases core

Summary

Store database connection strings in environment variables or a secrets manager; never commit them to source control. Use least-privilege users and SSL. Use this when deploying apps that connect to a database.

Intent: How-to

Quick answer

  • Keep connection strings out of code. Use env vars (e.g. DATABASE_URL) or a secrets manager. Load at runtime; never log or expose in errors.
  • Use a dedicated DB user with minimal privileges; avoid root or superuser in apps. Enable SSL in the connection string or driver config.
  • Rotate credentials periodically; use same mechanism for all environments with different values. Audit who can read secrets.

Prerequisites

Steps

  1. Use env or secrets

    Set DATABASE_URL or equivalent in environment or secrets manager. App reads at startup. No hardcoding; no commits.

  2. Least privilege and SSL

    Create app user with only required grants. Use sslmode=require or equivalent in connection string.

  3. Rotate and audit

    Rotate passwords or keys on schedule. Restrict access to secrets; log access where possible.

Summary

Store connection strings in env or secrets; use least-privilege users and SSL; rotate and audit.

Prerequisites

Steps

Step 1: Use env or secrets

Use DATABASE_URL from environment or secrets manager; never in code or logs.

Step 2: Least privilege and SSL

Use a limited DB user and SSL in the connection string.

Step 3: Rotate and audit

Rotate credentials; limit and audit who can read secrets.

Verification

  • No secrets in repo or logs; app connects with SSL and limited user.

Troubleshooting

Connection fails — Check env is set in runtime; verify network and SSL. Leak — Rotate immediately; audit and fix source.

Next steps

Continue to