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


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
Store PostgreSQL credentials in AWS Secrets Manager
Attach IAM role to EC2 (read permission for Secrets)
Use
docker exec
to runpg_dump
inside the containerExtract 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
permissionsAssign 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 leaksAccess 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.
Subscribe to my newsletter
Read articles from TechDave3573 directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
