blog

Best practices for securing PostgreSQL in hybrid environments

Sebastian Insausti

Published:

PostgreSQL adoption keeps accelerating, especially across hybrid architectures that span on-premises, private, and public clouds. But with that growth comes risk. Hybrid setups introduce new attack surfaces — from inconsistent firewall rules and multiple IAM systems to unsecured network traffic and misconfigured access.

For DBAs and DevOps teams, the consequences are high:

  • Financial losses: breaches cost an average of $4.45M (IBM Cost of a Data Breach Report).
  • Compliance violations: missteps can trigger GDPR, HIPAA, or PCI-DSS penalties.
  • Operational risk: poor user, role, or encryption management can create systemic vulnerabilities.

Securing PostgreSQL in this environment requires more than ad-hoc hardening — it demands consistent, centralized, and automated controls. This guide walks through PostgreSQL’s built-in security features, OS and network hardening, compliance practices, and how centralized management with ClusterControl simplifies security at scale.

Key PostgreSQL Security Features

PostgreSQL offers a full suite of integrated security features. Nevertheless, their efficacy hinges on accurate configuration and uniform application throughout all deployments.

Authentication and Encryption Best Practices

To secure PostgreSQL, prioritize these methods:

  • SCRAM-SHA-256 Authentication: Since PostgreSQL 10, this is the recommended method for password authentication. The password is never sent over the wire, and because SCRAM uses a challenge-response exchange, a captured authentication exchange can’t be replayed to log in. The method only works for roles whose passwords are stored as SCRAM hashes. Make sure password_encryption = ‘scram-sha-256’ is set (it’s the default since PostgreSQL 14), and reset any passwords that were originally stored as MD5.
  • Certificate-Based Authentication: This method is ideal for establishing mutual trust between clients and servers, and it’s commonly used for internal service-to-service authentication.
  • SSL/TLS Configuration: Enable encryption for network connections in postgresql.conf:
ssl = on
ssl_cert_file = '/etc/ssl/certs/your_cert.pem'
ssl_key_file = '/etc/ssl/private/your_key.pem'
ssl_ca_file = '/etc/ssl/certs/ca_cert.pem'

Requiring TLS and restricting access in pg_hba.conf

Setting ssl = on makes encrypted connections available, but it doesn’t make them mandatory. Which connections are allowed is decided in pg_hba.conf, and the record type matters. A host record matches TCP/IP connections whether or not they use SSL. A hostssl record matches only connections that use SSL. A rule like host all all 0.0.0.0/0 scram-sha-256 therefore lets any client that can reach port 5432 attempt a password login, encrypted or not, against any database and as any role.

A production configuration should require SSL and give each client only the access it needs:

# TYPE      DATABASE     USER          ADDRESS          METHOD
# Local administration over the Unix socket only
local            all                     postgres                                   peer
# Reject any TCP connection that isn't using SSL
hostnossl     all                     all                 all                       reject
# Application servers (on-prem): one database, one role, one subnet
hostssl         appdb               app_user      10.10.20.0/24      scram-sha-256
# Reporting host (cloud VPC): members of the reporting role only
hostssl         appdb               +reporting    10.30.5.15/32      scram-sha-256
# Streaming replication from the standby in the second region
hostssl         replication        replicator      10.20.10.0/24     scram-sha-256

A few points about this example:

PostgreSQL checks pg_hba.conf from top to bottom and uses the first record that matches the connection type, database, user, and client address. Since hostnossl ... reject sits near the top, every unencrypted TCP connection is refused before any other rule is considered. Strictly speaking, a connection that matches no record is rejected anyway. The explicit reject line is a safety net: if someone later adds a broader host rule further down, unencrypted clients still can’t use it.

Every accepting rule names a specific database, a specific role (the + prefix matches members of a group role), and the narrowest network that works. A /32 mask allows a single host. Avoid 0.0.0.0/0 or ::/0 in any rule that accepts connections.

The all keyword in the database column doesn’t cover physical replication connections. Replication needs its own record with the replication keyword, scoped to the replication role and the standby’s addresses.

pg_hba.conf controls who can connect, from where, and how they authenticate. It doesn’t control what they can do once connected. Pair it with least-privilege GRANTs, and don’t give application roles superuser or ownership of objects they only need to read or write.

Applying and verifying the change

Changes to pg_hba.conf take effect on a reload, so no restart is needed. Check the file for errors first:

SELECT line_number, type, database, user_name, address, auth_method, error
FROM pg_hba_file_rules;

Then reload:

SELECT pg_reload_conf();

If the file contains errors, PostgreSQL logs them and keeps the previous rules.

To confirm unencrypted connections are refused, connect from an allowed client with SSL disabled:

psql "host=db1.example.com dbname=appdb user=app_user sslmode=disable"

It should fail with an error like: pg_hba.conf rejects connection for host “10.10.20.5”, user “app_user”, database “appdb”, no encryption.

To check which current sessions are encrypted:

SELECT a.usename, a.client_addr, s.ssl, s.version, s.cipher
FROM pg_stat_ssl s
JOIN pg_stat_activity a USING (pid)
WHERE a.backend_type = 'client backend';

On the client side, hostssl guarantees the connection is encrypted, but it doesn’t let the client confirm it’s talking to the real server. Configure clients with sslmode=verify-full and sslrootcert pointing to your CA certificate. This protects against man-in-the-middle attacks, which matter most in hybrid setups where traffic crosses networks you don’t control. Treat pg_hba.conf rules as one layer alongside firewall rules and listen_addresses, not as a replacement for them.

Row-Level Security (RLS)

Row-Level Security in PostgreSQL provides granular access control, directly within the database. For instance:

ALTER TABLE salaries ENABLE ROW LEVEL SECURITY;
CREATE POLICY employee_policy
  ON salaries
  FOR SELECT
  USING (employee_id = current_setting('app.current_user_id')::int);

This is extremely useful for multi-tenant applications or environments where the principle of least privilege is critical.

OS and Network Hardening

Securing PostgreSQL, especially in hybrid environments, relies heavily on hardening the underlying operating system and network. This foundational defense is crucial against unauthorized access and data breaches.

  • Restrict Listening Addresses: listen_addresses in postgresql.conf controls which of the server’s own network interfaces PostgreSQL listens on. Set it to ‘localhost’ if only local applications connect, or to the specific interface addresses clients should use (e.g., ‘127.0.0.1, 10.10.20.10’) rather than ‘*’. Changing it requires a restart. Use pg_hba.conf and the firewall to control which client addresses are allowed.
  • Restrict Superuser Access: Superuser roles in PostgreSQL (e.g., postgres) possess the highest level of privileges, capable of bypassing all permission checks, creating/dropping databases, and managing user roles. Misuse of or compromising a superuser account can lead to catastrophic data loss or unauthorized access. 
  • Harden operating systems: Restrict network access to port 5432 with firewalls (e.g., iptables -A INPUT -p tcp --dport 5432 -s <trusted_ip_address> -j ACCEPT then iptables -A INPUT -p tcp --dport 5432 -j DROP), implement MAC (SELinux/AppArmor), log security events, keep all software patched, disable unneeded services, and set correct file permissions for PostgreSQL data and configuration files.
  • Physical security for on-prem nodes: While cloud nodes generally have robust physical security, on-premises PostgreSQL nodes require dedicated attention. This includes strictly controlled access (biometrics, keycards, surveillance), environmental protection (cooling, UPS, generators), tamper detection (locks, seals, intrusion systems), accurate hardware inventory, and regular disaster recovery plan testing.

Manual vs. ClusterControl: Pros and Cons of PostgreSQL Security Management

Effectively securing PostgreSQL deployments, especially in complex hybrid environments, presents significant challenges. Organizations often face a critical decision: opt for a meticulous manual approach or leverage a centralized management solution like ClusterControl. Both methods offer distinct advantages and disadvantages, impacting control, complexity, scalability, and compliance.

Manual Setup: Full Control, High Complexity

Manual PostgreSQL security offers maximum control, ideal for organizations prioritizing autonomy and avoiding third-party tools. Administrators can fine-tune all parameters, including network, authentication, user permissions, and encryption.

Pros:

  • Fine-grained control over every node’s configuration:

    Administrators can customize security settings for each PostgreSQL instance independently, allowing for highly specific and unique configurations tailored to individual application requirements or compliance mandates — this level of detail can be critical for highly sensitive data or niche security policies.
  • No vendor dependencies or additional tooling:

    Eliminating external tools reduces the attack surface by minimizing the number of software components and potential vulnerabilities introduced by third-party integrations. It also avoids licensing costs and simplifies the overall technology stack.

Cons:

  • Error-prone at scale:

    As the number of PostgreSQL instances grows across different environments (development, staging, production) or geographical regions, the likelihood of human error increases dramatically. Inconsistent configurations can lead to security gaps, performance issues, and operational inefficiencies.
  • Time-consuming changes, e.g., updating SSL certs on 20+ nodes:

    Routine security tasks, such as rotating SSL certificates, patching vulnerabilities, or updating access rules, become incredibly arduous and time-intensive when performed manually across numerous nodes. This can lead to delays in applying critical security updates, leaving systems exposed for longer periods.
  • Risk of configuration drift between environments(dev, staging, prod):

    Without a centralized enforcement mechanism, it’s common for security configurations to diverge between environments. This “configuration drift” makes it difficult to maintain a consistent security posture and can inadvertently create exploitable weaknesses. For example, a hardening measure applied in production might be overlooked in a staging environment.
  • Continuous compliance checks are labor-intensive and error-prone:

    Manually verifying that all PostgreSQL instances adhere to internal security policies and external regulatory compliance standards, e.g., GDPR, HIPAA, PCI DSS, is a labor-intensive and error-prone process. Generating comprehensive audit trails and demonstrating continuous compliance becomes a significant operational burden.

Centralized PostgreSQL Security with ClusterControl

ClusterControl addresses the inherent limitations of manual security management by providing a centralized platform for automating and orchestrating PostgreSQL at scale. It offers a unified interface to manage configurations across diverse environments, including on-premises, cloud, and hybrid cloud deployments.

ClusterControl simplifies PostgreSQL security at scale. Key advantages include;

  • Apply SSL/TLS settings estate-wide from a single UI:

    Instead of manually configuring SSL/TLS on each server, ClusterControl allows administrators to define and deploy encryption settings universally. This ensures consistent data in-transit encryption, simplifying certificate management and reducing the risk of misconfiguration.
  • Enforce pg_hba.conf rules and user roles consistently across all nodes:

    The pg_hba.conf file is critical for controlling client authentication and access. ClusterControl enables the centralized management and enforcement of these rules, preventing unauthorized access and ensuring that all PostgreSQL instances adhere to defined access policies without manual intervention on each server.
  • Centralized auditing of configuration changes and access logs:

    Comprehensive auditing is vital for security and compliance. ClusterControl centralizes the logging and auditing of configuration changes and access attempts. This provides a clear, immutable record of who made what changes and who accessed the database, significantly simplifying incident response, forensic analysis, and compliance reporting.

That said, automation’s power implies propagation risks that need to be respected, such as;

  • Requires careful policy design, testing, and version control to avoid risks:

    While ClusterControl simplifies management, administrators must ensure policies reflect organizational security mandates. The power of centralized management means misconfigurations can spread rapidly, so rigorous testing, version-controlled templates, and a solid understanding of their security impact are essential to maintain a robust posture.

While manual control provides unmatched granularity, ClusterControl emphasizes consistency and scalability — which become critical as deployments grow.

Implementing Best Practices

SSL (Secure Sockets Layer) Configuration:

Implementing SSL for PostgreSQL connections is paramount for encrypting data in transit, protecting sensitive information from eavesdropping, and tampering. This is especially crucial in hybrid environments where data traverses various networks, including public ones. The postgresql.conf file is the primary configuration file for enabling SSL.

SSL Example:

# postgresql.conf

ssl = on

ssl_cert_file = '/etc/postgresql/ssl/server.crt'

ssl_key_file = '/etc/postgresql/ssl/server.key'

ssl_ca_file = '/etc/postgresql/ssl/rootCA.crt'
  • ssl = on: Enables SSL support. PostgreSQL accepts both SSL and non-SSL connections on the same port, so use hostssl rules in pg_hba.conf (covered earlier) to make encryption mandatory.
  • ssl_cert_file: Specifies the path to the server’s SSL certificate file. This certificate is presented to clients to verify the server’s identity.
  • ssl_key_file: The server’s private key, used during the TLS handshake to prove the server owns its certificate. Keep it private: PostgreSQL won’t start if the file is readable by other users (it must be 0600 when owned by the database user, or 0640 when owned by root).
  • ssl_ca_file: The CA certificate(s) the server uses to verify client certificates. It’s required for certificate authentication (the cert method or the clientcert option). Clients verify the server with their own copy of the CA, set through sslrootcert.

RLS (Row Level Security) Configuration:

Row Level Security provides granular control over data access, allowing database administrators to define policies that restrict which rows a specific user can view or modify. This is particularly useful in multi-tenant applications or environments where different users or roles should only see data relevant to them.

RLS Example:

ALTER TABLE transactions ENABLE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation

  ON transactions

  USING (tenant_id = current_setting('app.tenant_id')::uuid);
  • ALTER TABLE transactions ENABLE ROW LEVEL SECURITY: This statement enables RLS for the transactions table, meaning that any queries against this table will now be subject to defined security policies.
  • CREATE POLICY tenant_isolation: This command creates a new RLS policy named tenant_isolation.
    • ON transactions: Specifies that this policy applies to the transactions table.
    • USING (tenant_id = current_setting(‘app.tenant_id’)::uuid): This is the core of the policy. It dictates that a row in the transactions table is accessible only if its tenant_id matches the value of the app.tenant_id application setting, cast as a UUID. This ensures that users or applications can only access data belonging to their assigned tenant.

Keep in mind that superusers and roles with the BYPASSRLS attribute always bypass RLS, and so does the table owner unless you run ALTER TABLE transactions FORCE ROW LEVEL SECURITY. The application should connect as a role that doesn’t own the table. Also, current_setting(‘app.tenant_id’) raises an error if the setting hasn’t been set in the session. Using current_setting(‘app.tenant_id’, true) returns NULL instead, so the policy simply returns no rows.

Secrets Management

Effective secrets management is a critical component of a secure PostgreSQL environment, especially in hybrid or cloud-native deployments. Secrets include sensitive credentials like database superuser passwords, API keys, and certificate passwords.

By implementing a comprehensive secrets management strategy, organizations can:

  • Minimize the risk of credential theft and misuse.
  • Automate the lifecycle of sensitive information.
  • Improve compliance with security policies and regulations.
  • Enhance overall operational security and efficiency.

Monitoring & Alerting for Security Events

Centralized Monitoring in Hybrid Setups

ClusterControl offers a comprehensive solution for centralized monitoring and management of PostgreSQL clusters, regardless of their deployment location. It meticulously gathers a wide array of critical data points from every single node, whether it resides in the cloud or on-premises. This data includes vital logs, detailed query statistics to understand performance and bottlenecks, records of all authentication attempts for security auditing, and a wealth of performance metrics. By consolidating this information into a single, unified view, ClusterControl empowers administrators with unparalleled visibility and control over their entire PostgreSQL ecosystem, facilitating proactive issue resolution, performance optimization, and robust security posture across hybrid environments.

screenshot of clustercontrol home ui

Alerts and Anomaly Detection

Setting up robust security-specific thresholds is a critical component of maintaining a secure PostgreSQL environment, especially in hybrid cloud architectures. These thresholds act as early warning systems, alerting administrators to potential security breaches or policy violations. To facilitate real-time security monitoring and incident response, ClusterControl offers seamless integration with industry-leading tools. This integration enables a centralized and proactive approach to security management:

  • Prometheus: For monitoring PostgreSQL metrics, including performance and security-related data. It can collect data on failed logins, configuration file checksums, and SSL status, providing a comprehensive view of the database’s health and security posture.
  • Grafana: To visualize the data collected by Prometheus, creating intuitive dashboards that highlight security trends, anomalies, and active threats. The dashboards allow administrators to gain immediate insights into security events and prioritize their response.
  • PagerDuty (or similar): For reliable and actionable incident alerting. When a security threshold is breached, PagerDuty can escalate alerts to the appropriate on-call personnel, ensuring that critical security incidents are addressed promptly, minimizing potential damage.
  • Slack: For real-time communication and collaboration among security teams. Integration with Slack allows for instant notifications of security alerts, facilitating rapid discussion, analysis, and coordinated response efforts to mitigate threats effectively.

By combining well-defined security thresholds with powerful monitoring and alerting integrations, organizations can establish a proactive security posture, safeguarding their PostgreSQL deployments in complex hybrid environments.

Compliance & Hardening

Meeting Regulatory Standards

For organizations where security is paramount, adhering to compliance standards is not merely an option but a strict necessity. PostgreSQL, when properly hardened and configured, offers robust capabilities to support various stringent regulatory frameworks.

• GDPR: Data minimization via RLS, auditing via pgAudit.

• HIPAA: Encrypt sensitive data in transit and at rest.

• PCI-DSS: Enforce strict role access and monitor all login attempts.

Auditing with pgAudit + ClusterControl

The pgAudit extension provides detailed session and object audit logging, covering statements such as reads, writes, DDL, and role changes. Connection logging is handled separately by log_connections and log_disconnections. Add pgaudit to shared_preload_libraries in postgresql.conf, keeping any libraries already listed there, set pgaudit.log, and restart:

shared_preload_libraries = 'pg_stat_statements,pgaudit'
pgaudit.log = 'write, ddl, role'

While pgAudit generates detailed logs, managing them across a distributed PostgreSQL infrastructure is challenging. ClusterControl addresses this by centralizing the audit logs from all managed nodes, providing a single pane of glass for security monitoring. This enables quick searching for events, tracking user activity, identifying breaches, and streamlining compliance reporting, ensuring a robust security posture for PostgreSQL.

screenshot of clustercontrol cluster system log ui

Wrapping up

Securing PostgreSQL in hybrid environments isn’t a one-time project — it’s a continuous process of authentication hardening, encryption, role management, monitoring, and compliance enforcement. PostgreSQL provides the foundation with features like SCRAM, TLS, RLS, and pgAudit.

ClusterControl extends these capabilities, giving DBAs and DevOps teams:

  • Centralized visibility across all nodes.
  • Automated configuration and certificate management.
  • Unified auditing and compliance reporting.
  • Real-time monitoring and alerting for proactive defense.

With centralized management, you can prevent misconfigurations, enforce policies consistently, and reduce both risk and operational overhead.

Get started in minutes: Install ClusterControl directly from this post and secure your PostgreSQL deployments with a free 30-day Enterprise trial.

Script Installation Instructions

The installer script is the simplest way to get ClusterControl up and running. Run it on your chosen host, and it will take care of installing all required packages and dependencies.

Offline environments are supported as well. See the Offline Installation guide for more details.

On the ClusterControl server, run the following commands:

wget https://severalnines.com/downloads/cmon/install-cc
chmod +x install-cc

With your install script ready, run the command below. Replace S9S_CMON_PASSWORD and S9S_ROOT_PASSWORD placeholders with your choice password, or remove the environment variables from the command to interactively set the passwords. If you have multiple network interface cards, assign one IP address for the HOST variable in the command using HOST=<ip_address>.

S9S_CMON_PASSWORD=<your_password> S9S_ROOT_PASSWORD=<your_password> HOST=<ip_address> ./install-cc # as root or sudo user

After the installation is complete, open a web browser, navigate to https://<ClusterControl_host>/, and create the first admin user by entering a username (note that “admin” is reserved) and a password on the welcome page. Once you’re in, you can deploy a new database cluster or import an existing one.

The installer script supports a range of environment variables for advanced setup. You can define them using export or by prefixing the install command.

See the list of supported variables and example use cases to tailor your installation.

Other Installation Options

Helm Chart

Deploy ClusterControl on Kubernetes using our official Helm chart.

Ansible Role

Automate installation and configuration using our Ansible playbooks.

Puppet Module

Manage your ClusterControl deployment with the Puppet module.

ClusterControl on Marketplaces

Prefer to launch ClusterControl directly from the cloud? It’s available on these platforms:

Subscribe below to be notified of fresh posts