PostgreSQL Backup with AWS Secrets Manager โ€“ Secure Automation in Docker on EC2

TechDave3573TechDave3573
2 min read

If you're running PostgreSQL inside a Docker container on AWS EC2, password management during backups becomes a real concern. Hardcoding PGPASSWORD or relying on .pgpass is not acceptable in secure environments.

So I turned to AWS Secrets Manager โ€” and for a Docker + EC2 setup, it's the most practical solution I've found.


๐Ÿ” System Overview: Secrets Manager + Docker + pg_dump

  1. Store PostgreSQL credentials in AWS Secrets Manager

  2. Attach IAM role to EC2 (read permission for Secrets)

  3. Use docker exec to run pg_dump inside the container

  4. Extract credentials via AWS CLI in the host and pass them into the container


๐Ÿ“ Secrets Format Example

Secret name: postgresql/backup

{
  "host": "localhost",
  "port": "5432",
  "username": "postgres",
  "password": "yourPassword",
  "dbname": "your_db"
}

๐Ÿ” Attach IAM Role to EC2

  • Make sure the role has secretsmanager:GetSecretValue permissions

  • Assign it via instance profile, so AWS CLI works without keys


๐Ÿงฉ Backup Script (AWS CLI + jq + Docker)

#!/bin/bash

secret=$(aws secretsmanager get-secret-value \
  --secret-id postgresql/backup \
  --query SecretString \
  --output text)

export DB_HOST=$(echo $secret | jq -r .host)
export DB_PORT=$(echo $secret | jq -r .port)
export DB_USER=$(echo $secret | jq -r .username)
export DB_PASS=$(echo $secret | jq -r .password)
export DB_NAME=$(echo $secret | jq -r .dbname)

docker exec -e PGPASSWORD=$DB_PASS my_postgres \
  pg_dump -U $DB_USER -h $DB_HOST -p $DB_PORT $DB_NAME > /home/backup/pg_backup.sql

Youโ€™ll need jq installed and AWS CLI configured on your EC2 instance.


โœ… Why This Approach Works

  • No .pgpass, no hardcoded passwords, no plaintext leaks

  • Access control managed via IAM โ€” auditable and secure

  • Works with cron, logrotate, and container remains online during backup


๐Ÿง  Final Thoughts

Backups must be reliable, but credentials must stay secure. This method is one of the rare ways to meet both goals simultaneously.

If you're running PostgreSQL in Docker on EC2, this setup isn't just nice to have โ€” it's essential.

Itโ€™s been running smoothly for me in production, with zero backup incidents. Not perfect โ€” but in ops, stability beats idealism.

0
Subscribe to my newsletter

Read articles from TechDave3573 directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

TechDave3573
TechDave3573