TL;DR
Don’t store database passwords directly in your web app code or config files! Use a password manager, environment variables, or a dedicated secrets management system. Rotate passwords regularly and limit database user permissions.
Securing Database Passwords: A Step-by-Step Guide
- Understand the Risks
- Storing passwords in plain text is a major security flaw. If your app or server is compromised, attackers have immediate access to your database.
- Hardcoding passwords into code makes it difficult to change them quickly and consistently across multiple applications.
- Version control systems (like Git) can accidentally expose passwords if they’re committed to a repository.
- Choose a Secure Storage Method
- Password Manager: Tools like HashiCorp Vault, 1Password Business, or LastPass Enterprise are designed specifically for managing secrets. They offer encryption, access control, and audit logs. This is the most secure option but requires setup and maintenance.
- Environment Variables: Store passwords as environment variables on your server. This keeps them out of your codebase. Access them within your application code.
# Example in a .env file DATABASE_PASSWORD=your_strong_passwordAccessing the variable (Python example):
import os database_password = os.environ.get('DATABASE_PASSWORD') - Dedicated Secrets Management Systems: Cloud providers (AWS, Azure, Google Cloud) offer services like AWS Secrets Manager, Azure Key Vault, and Google Cloud Secret Manager. These integrate well with their respective platforms.
- Rotate Passwords Regularly
- Change your database passwords on a scheduled basis (e.g., every 90 days).
- Automate password rotation whenever possible using scripts or tools provided by your chosen storage method.
- Limit Database User Permissions
- Create separate database users for each web application.
- Grant each user only the minimum necessary permissions required to perform their tasks (e.g., read-only access if they don’t need to write data).
- Avoid using the ‘root’ or ‘admin’ database account in your applications.
- Encryption at Rest and in Transit
- Ensure your database is encrypted at rest (data stored on disk) to protect against physical theft of storage media.
- Use SSL/TLS encryption for all connections between your web applications and the database server to prevent eavesdropping.
# Example MySQL connection string with SSL mysql_connect(host='your_host', user='your_user', password='your_password', ssl_ca='/path/to/ssl_cert.pem') - Audit Logging
- Enable audit logging on your database server to track who is accessing the database and what changes they are making.
- Regularly review audit logs for suspicious activity.
- Avoid Storing Passwords in Version Control
- Never commit passwords directly into your Git repository or any other version control system.
- Use a .gitignore file to exclude files containing sensitive information (e.g., config files with hardcoded passwords).

