DropVPS Team
Writer: Cooper Reagan
Securing PostgreSQL Databases on VPS: A Step-by-Step Guide

Table of Contents
What you will read?
Securing your PostgreSQL database on a VPS is a critical step to protect sensitive data, prevent unauthorized access, and ensure the integrity of your database. PostgreSQL is a powerful and flexible open-source relational database management system (RDBMS), but like any database, it requires proper security measures to safeguard your data.
PostgreSQL offers several built-in features that help in securing your database, such as authentication, access control, and encryption. However, it is essential to configure these features correctly and implement additional security practices to create a secure environment.
Configuring PostgreSQL for Enhanced Security

Configuring PostgreSQL for enhanced security involves several steps to ensure that your database is protected from unauthorized access and vulnerabilities. PostgreSQL offers a variety of configuration options that allow you to tighten security and control how the database is accessed and used. Below are some of the key configuration practices for enhancing PostgreSQL security:
- Configure PostgreSQL Authentication:
- PostgreSQL supports multiple authentication methods such as password-based authentication, certificate-based authentication, and more. The most common and secure approach is to use md5 or scram-sha-256 for password-based authentication.
- In the
pg_hba.conffile, ensure only trusted IP addresses or hostnames are allowed to connect to the database.
- Enforce Strong Password Policies:
- Configure PostgreSQL to enforce strong password policies to ensure that users create secure passwords. This can be done using tools like pgcrypto or configuring a password complexity policy.
- Restrict Database Access:
- Use the pg_hba.conf file to specify which users and IP addresses are allowed to access the database. Restrict access to trusted sources only.
- Enable SSL for Secure Connections:
- Enable SSL encryption to ensure data is transmitted securely over the network. Modify the
postgresql.conffile to enable SSL and configure the necessary certificates.
- Enable SSL encryption to ensure data is transmitted securely over the network. Modify the
- Limit Superuser Privileges:
- Superuser accounts have full control over the database. It is a best practice to minimize the use of superuser accounts and instead, assign users with specific roles and limited privileges.
- Regularly Update PostgreSQL:
- Ensure that you are using the latest version of PostgreSQL, as new releases often include important security fixes. Use automated tools to keep your system updated regularly.
- Audit Logging:
- Enable logging to track database activities, such as successful and failed login attempts, changes to database objects, and more. This helps to monitor any suspicious activity.
By properly configuring PostgreSQL with these security measures, you ensure a robust and secure database environment that can withstand potential attacks and unauthorized access attempts.
Setting Up Firewall and Network Access Restrictions
Setting up a firewall and enforcing network access restrictions are crucial steps in securing your PostgreSQL database on a VPS. These measures ensure that only authorized users and systems can access your database, while blocking unwanted traffic from malicious sources. Below are the steps to configure firewall rules and set up network access restrictions:
Configuring a Firewall on Your VPS
The first step is to configure a firewall on your VPS to restrict access to your PostgreSQL server. The most common firewall software used on Linux servers is UFW (Uncomplicated Firewall) or iptables. With either option, you can specify which IP addresses are allowed to connect to your VPS and block all others.
Example of configuring UFW to allow PostgreSQL connections from specific IP:
sudo ufw allow from 192.168.1.100 to any port 5432
sudo ufw enable
This command ensures that only the IP address 192.168.1.100 is allowed to connect to the PostgreSQL port (5432). You can modify the IP address to reflect your network environment.
Restricting Remote Access in PostgreSQL
PostgreSQL’s pg_hba.conf file controls which hosts can connect to the database and which authentication methods are used. To enhance security, restrict connections to the database to only trusted IPs or hostnames.
Example configuration in pg_hba.conf to allow only specific IP addresses:
host all all 192.168.1.100/32 md5
host all all 192.168.1.101/32 md5
This configuration ensures that only connections from the IPs 192.168.1.100 and 192.168.1.101 are allowed.
Limiting PostgreSQL Access to Localhost (for development)
If you’re setting up PostgreSQL for development or testing purposes and want to limit access to the local machine, you can configure PostgreSQL to listen only on localhost. This can be done by modifying the postgresql.conf file.
In postgresql.conf, set the listen_addresses to 'localhost':
listen_addresses = 'localhost'
This will ensure that PostgreSQL only accepts connections from the same machine (localhost) and denies any external connections.
Using VPN for Secure Access
For a more secure connection to your PostgreSQL database, you may want to use a Virtual Private Network (VPN). A VPN encrypts the connection between your client machine and the VPS, providing an additional layer of security. Only machines connected to the VPN will be able to access the PostgreSQL server.
Restricting Port Access on Your VPS
In addition to restricting PostgreSQL connections, it’s important to restrict access to other unnecessary ports on your VPS. For example, if your server doesn’t need to have HTTP (port 80) or SSH (port 22) open to the public, close these ports to prevent unauthorized access.
Example of restricting access to HTTP and SSH using UFW:
sudo ufw deny 22
sudo ufw deny 80
sudo ufw reload
These commands will block external access to ports 22 and 80, making your VPS more secure.
By configuring a proper firewall and enforcing strict network access controls, you can significantly reduce the chances of unauthorized access to your PostgreSQL database.
Enabling SSL for Secure PostgreSQL Connections

Enabling SSL (Secure Sockets Layer) for PostgreSQL ensures that data transmitted between your server and clients is encrypted, providing a higher level of security for your database connections. Below are the steps to enable and configure SSL for secure PostgreSQL connections on your VPS:
Generating SSL Certificates
Before enabling SSL, you need to generate the necessary SSL certificates. You will need a server certificate, server key, and CA (Certificate Authority) certificate. You can either use a certificate from a trusted Certificate Authority or create a self-signed certificate for testing purposes.
To generate a self-signed certificate and key, run the following commands:
mkdir -p /etc/postgresql/ssl
cd /etc/postgresql/ssl
openssl req -new -newkey rsa:2048 -days 365 -nodes -x509 -keyout server.key -out server.crt
chmod 600 server.key
This will generate server.crt and server.key files in the /etc/postgresql/ssl directory. You should ensure that these files are kept secure and have the appropriate permissions.
Configuring PostgreSQL to Use SSL
After generating the certificates, you need to configure PostgreSQL to use SSL by modifying the PostgreSQL configuration files. Edit the postgresql.conf file:
sudo nano /etc/postgresql/{version}/main/postgresql.conf
Find and update the following settings:
ssl = on
ssl_cert_file = '/etc/postgresql/ssl/server.crt'
ssl_key_file = '/etc/postgresql/ssl/server.key'
ssl_ca_file = '/etc/postgresql/ssl/ca.crt' # optional if using a CA certificate
This configuration enables SSL for the PostgreSQL server and points to the certificate and key files you generated earlier. If you have a CA certificate, you can also specify the ssl_ca_file to validate client certificates.
Updating pg_hba.conf for SSL Connections
The pg_hba.conf file controls client authentication. To require SSL connections, modify this file to specify that SSL is needed for client connections.
Edit the pg_hba.conf file:
sudo nano /etc/postgresql/{version}/main/pg_hba.conf
Update the lines for local and remote connections to require SSL:
hostssl all all 0.0.0.0/0 md5
This change ensures that all client connections over the network require SSL encryption.
Restart PostgreSQL Service
After making the changes to the configuration files, restart the PostgreSQL service to apply the new settings.
sudo systemctl restart postgresql
Verifying SSL Connection
Once SSL is enabled, you can verify that SSL connections are working correctly by connecting to PostgreSQL using the psql client. You can check if SSL is being used by running the following SQL query:
SHOW ssl;
If SSL is enabled, this query should return on.
Client-side Configuration
On the client-side, when connecting to PostgreSQL, use the sslmode option to enforce SSL usage. You can connect to your PostgreSQL database using the following command:
psql -h your_server_ip -U your_user -d your_database -p 5432 sslmode=require
The sslmode=require option ensures that the client uses SSL for the connection.
By enabling SSL for PostgreSQL, you ensure that all data exchanged between your server and clients is encrypted, protecting sensitive information from being exposed to unauthorized access.
Configuring User Authentication and Roles in PostgreSQL
PostgreSQL provides a robust authentication and authorization system for managing database users and roles. Configuring user authentication and roles correctly is essential for ensuring secure and efficient access to your database. Below are the steps to configure user authentication and roles in PostgreSQL on your VPS:
- Creating a New Role (User): In PostgreSQL, roles are used to represent users or groups of users. To create a new role, you can use the following SQL command within the PostgreSQL shell (
psql):CREATE ROLE new_user WITH LOGIN PASSWORD 'your_password';This command creates a new role called
new_userwith the ability to log in and a specified password. - Assigning Privileges to Roles: After creating a role, you can assign specific privileges to it. For example, to give the role permission to create databases, use:
ALTER ROLE new_user CREATEDB;You can assign other privileges as needed, such as
CREATEROLE,SUPERUSER, or specific permissions on databases and tables. - Granting Access to Databases: To allow a role to access a specific database, you need to grant it permission to connect to that database. You can use the following command to grant connection rights:
GRANT CONNECT ON DATABASE your_database TO new_user;Additionally, to grant specific table or schema-level privileges, you can use commands like:
GRANT SELECT, INSERT, UPDATE ON ALL TABLES IN SCHEMA public TO new_user; - Configuring Authentication Methods: PostgreSQL supports different authentication methods, which can be configured in the
pg_hba.conffile. This file controls how clients can authenticate with the PostgreSQL server.Thepg_hba.conffile is located at/etc/postgresql/{version}/main/pg_hba.conf. To configure authentication, you need to specify the method for each connection type (local, host, etc.). For example:# TYPE DATABASE USER ADDRESS METHOD host all all 192.168.1.0/24 md5 host all new_user 192.168.1.10/32 md5In this configuration,
md5is used for password authentication. Other authentication methods includetrust,peer,ident, andscram-sha-256. - Setting Password Expiration: You can configure password expiration for users in PostgreSQL. For example, to set an expiration time of 90 days for a user’s password:
ALTER ROLE new_user VALID UNTIL '2024-03-01';This ensures that the user must change their password by the specified date.
- Revoking Privileges: If you need to revoke a user’s privileges, you can use the
REVOKEcommand. For example, to revoke theCREATEDBprivilege:ALTER ROLE new_user NOCREATEDB; - Dropping a User Role: If you no longer need a user role, you can remove it from the system with the following command:
DROP ROLE new_user;This command will remove the role and all its associated privileges.
- Testing User Authentication: After configuring user authentication and roles, it’s important to test the setup. Try logging in with the created user role to verify that the authentication works and the assigned privileges are functioning correctly. Use the following command to connect as the new user:
psql -h your_server_ip -U new_user -d your_databaseIf configured correctly, the user should be able to connect to the database with the appropriate privileges.
Updating PostgreSQL and Patching Vulnerabilities
Regular updates and patching of PostgreSQL are essential for maintaining database security, performance, and stability. In this section, we’ll cover how to update PostgreSQL on your VPS and apply patches to fix known vulnerabilities.
Checking the Current PostgreSQL Version
Before updating, it’s important to check the current version of PostgreSQL installed on your VPS. Use the following command to check the installed version:
psql --version
Updating PostgreSQL Using Package Manager
PostgreSQL is typically installed via a package manager like apt on Ubuntu/Debian-based systems or yum on CentOS/RHEL systems. To update PostgreSQL, follow the steps below based on your system:
- On Ubuntu/Debian-based systems, update the package list and upgrade PostgreSQL:
sudo apt update sudo apt upgrade postgresql - On CentOS/RHEL-based systems, use the following commands:
sudo yum update sudo yum upgrade postgresql
These commands will update PostgreSQL to the latest version available in the official repositories.
Updating PostgreSQL Repositories
In some cases, the official repositories might not contain the latest version of PostgreSQL. To ensure you have the latest version, you can add the PostgreSQL repository for your distribution. On Ubuntu/Debian systems, follow these steps:
- Import the PostgreSQL repository’s signing key:
wget -qO - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add - - Add the PostgreSQL repository:
sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ $(lsb_release -c | awk '{print $2}')-pgdg main" > /etc/apt/sources.list.d/pgdg.list' - Update the package list and install the latest version:
sudo apt update sudo apt upgrade postgresql
Patching Security Vulnerabilities
PostgreSQL, like any other software, can have vulnerabilities that need to be patched. Security patches are usually released by the PostgreSQL development team. To keep your system secure, it’s important to regularly check for updates and install patches. Use the following command to check for updates:
sudo apt update && sudo apt upgrade
Additionally, you can monitor PostgreSQL’s security mailing list or the official PostgreSQL website for announcements regarding vulnerabilities and patches.
Upgrading PostgreSQL Major Version
If you need to upgrade PostgreSQL to a newer major version (for example, from PostgreSQL 12 to PostgreSQL 13), follow these steps:
- Back up your databases:
pg_dumpall > backup.sql - Install the new version of PostgreSQL:
sudo apt install postgresql-13 - Upgrade the database to the new version:
sudo pg_upgradecluster 12 main - After upgrading, test the new version and make sure everything works as expected.
Restarting PostgreSQL
After performing an update or applying patches, you may need to restart PostgreSQL to apply the changes. You can restart PostgreSQL using the following command:
sudo systemctl restart postgresql
Verifying the Update
After updating or patching PostgreSQL, verify the installation by checking the version again:
psql --version
You should see the updated version number, confirming that the update was successful.