DropVPS Team
Writer: Cooper Reagan
Using PostgreSQL on VPS: Installation and Configuration

Table of Contents
What you will read?
PostgreSQL is widely used in both small-scale applications and large enterprise systems due to its scalability, performance, and reliability. It is suitable for handling large volumes of structured and unstructured data and supports complex queries and reporting needs.
Prerequisites and Preparing the VPS for PostgreSQL
Before installing PostgreSQL on your VPS, there are several essential steps to follow to ensure the system is ready for a smooth installation. Here’s a checklist to prepare your VPS for PostgreSQL:
Ensure VPS is Running a Supported Operating System:
PostgreSQL supports various Linux distributions, Windows, and macOS. For a VPS, a Linux-based system is commonly used, and you should make sure your server is running a supported version of one of the following:
- Ubuntu (20.04, 22.04, or newer)
- Debian (10, 11, or newer)
- CentOS/RHEL (7, 8 or newer)
- Fedora
You can verify your operating system by running:
uname -a
2. Update the VPS Operating System:
It is essential to ensure that your VPS is up-to-date with the latest security patches and updates. This will reduce the likelihood of any conflicts during installation.
- For Ubuntu/Debian-based systems:
sudo apt update && sudo apt upgrade -y - For CentOS/RHEL-based systems:
sudo yum update -y
3. Check for Available Disk Space:
PostgreSQL requires sufficient disk space to store the database and transaction logs. Ensure that your VPS has adequate disk space before proceeding with the installation.
- To check disk space:
df -h
4. Ensure Sufficient RAM:
PostgreSQL is memory-intensive, especially when handling larger databases or high traffic. Ensure that your VPS meets the minimum system requirements:
- At least 1GB of RAM (for smaller workloads).
- 2GB or more is recommended for production environments.
You can check available RAM with:
free -h
5. Ensure Network Access (for Remote Connections, if needed):
If you intend to access PostgreSQL remotely, ensure that your VPS has a public IP address and that the necessary ports (default PostgreSQL port is 5432) are open in the firewall.
To check if the port is open:
sudo ufw allow 5432/tcp # For Ubuntu/Debian-based systems
sudo firewall-cmd --zone=public --add-port=5432/tcp --permanent # For CentOS/RHEL
sudo firewall-cmd --reload # Reload firewall
6. Install Required Dependencies:
Ensure that your VPS has the necessary software dependencies installed for PostgreSQL to run smoothly. Some distributions may already have these packages, but it’s best to double-check.
For Ubuntu/Debian:
sudo apt install wget ca-certificates -y
For CentOS/RHEL:
7. Backup Your VPS (Optional but Recommended):
Before proceeding with the installation, it’s a good idea to create a backup of your VPS. This will protect your system in case anything goes wrong during the PostgreSQL installation process.
You can create backups using your hosting provider’s control panel or use command-line tools like rsync.
Installing PostgreSQL on VPS
Once your VPS is properly prepared, you can proceed with the installation of PostgreSQL. The installation process differs slightly depending on the Linux distribution you are using, but the general steps are similar. Below are the steps for Ubuntu/Debian and CentOS/RHEL systems.
1. Installing PostgreSQL on Ubuntu/Debian:
Step 1: Add PostgreSQL APT Repository (if needed)
PostgreSQL packages are available in the default repository for most distributions. However, you may want to install the latest version of PostgreSQL, which can be done by adding the official PostgreSQL APT repository.
sudo apt install wget ca-certificates -y
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo tee /etc/apt/trusted.gpg.d/postgresql.asc
echo "deb http://apt.postgresql.org/pub/repos/apt/ $(lsb_release -c | awk '{print $2}')-pgdg main" | sudo tee /etc/apt/sources.list.d/pgdg.list
Step 2: Update Package Lists
After adding the repository, update the package list:
sudo apt update
Step 3: Install PostgreSQL
Install PostgreSQL by running the following command:
sudo apt install postgresql postgresql-contrib -y
Step 4: Verify Installation
To verify that PostgreSQL is installed, check the version with:
psql --version
2. Installing PostgreSQL on CentOS/RHEL:
Step 1: Add PostgreSQL Yum Repository
For CentOS or RHEL, you need to install the PostgreSQL repository manually.
sudo yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-centos10-13-2.noarch.rpm
Step 2: Disable the Default PostgreSQL Module
RHEL 8 and CentOS 8 ship with a PostgreSQL module that you may want to disable before installing the PostgreSQL packages.
sudo dnf -qy module disable postgresql
Once the repository is added, install PostgreSQL and its contributed modules:
sudo yum install postgresql13 postgresql13-server postgresql13-contrib -y
Step 4: Initialize PostgreSQL Database
After installation, initialize the PostgreSQL database:
sudo /usr/pgsql-13/bin/postgresql-13-setup initdb
Step 5: Start and Enable PostgreSQL Service
Enable and start PostgreSQL to begin using it:
sudo systemctl enable postgresql-13
sudo systemctl start postgresql-13
Step 6: Verify Installation
To verify that PostgreSQL is running, check its status:
sudo systemctl status postgresql-13
3. Post-Installation Configuration:
Step 1: Switch to the PostgreSQL User
PostgreSQL creates a default user called postgres during installation. To access the PostgreSQL command-line interface, switch to the postgres user:
sudo -i -u postgres
Step 2: Access PostgreSQL Command Line
To enter the PostgreSQL command-line interface, run:
psql
You should now be logged into the PostgreSQL shell, where you can execute SQL commands.
Configuring PostgreSQL for the First Time
After installing PostgreSQL on your VPS, there are a few configuration steps to ensure that the database is set up properly and ready for use. Here’s a step-by-step guide for configuring PostgreSQL for the first time:
1. Switch to the PostgreSQL User:
PostgreSQL runs under a dedicated user account called postgres. To perform administrative tasks, you need to switch to this user.
sudo -i -u postgres
2. Access the PostgreSQL Command-Line Interface:
Once logged in as the postgres user, you can access the PostgreSQL command line tool (psql) by typing:
psql
This will take you to the PostgreSQL interactive terminal where you can execute SQL commands.
3. Set the Password for the PostgreSQL User:
By default, the postgres user does not have a password set. It is recommended to set a password for security reasons. To set the password, run the following command inside the PostgreSQL command-line interface:
\password postgres
You will be prompted to enter a new password. Make sure to choose a strong password.
4. Create a New Database:
PostgreSQL allows you to create databases for your applications. You can create a new database with the following SQL command:
CREATE DATABASE my_database;
5. Create a New Database User:
It’s best practice to create a dedicated user for your applications instead of using the postgres user. To create a new user, run the following SQL command:
CREATE USER my_user WITH PASSWORD 'my_password';
Replace my_user with your desired username and my_password with a strong password for the new user.
6. Grant Privileges to the New User:
After creating a new user, you need to grant them the necessary privileges to interact with the database. To allow the user to connect to the database and perform operations, use the following command:
GRANT ALL PRIVILEGES ON DATABASE my_database TO my_user;
Replace my_database and my_user with the names you chose earlier.
7. Allow Remote Connections (Optional):
By default, PostgreSQL is configured to only allow local connections. If you want to access PostgreSQL remotely, you need to modify the configuration.
- Step 1: Edit
postgresql.conf
Open thepostgresql.conffile in a text editor:sudo nano /etc/postgresql/13/main/postgresql.conf # For Ubuntu/Debian sudo nano /var/lib/pgsql/13/data/postgresql.conf # For CentOS/RHELFind the line
#listen_addresses = 'localhost'and change it to:listen_addresses = '*'This allows PostgreSQL to listen for connections from any IP address.
- Step 2: Edit
pg_hba.conf
Open thepg_hba.conffile:sudo nano /etc/postgresql/13/main/pg_hba.conf # For Ubuntu/Debian sudo nano /var/lib/pgsql/13/data/pg_hba.conf # For CentOS/RHELAdd the following line at the end of the file to allow remote connections:
host all all 0.0.0.0/0 md5This allows all users to connect from any IP address using password authentication.
- Step 3: Restart PostgreSQL
After making changes to the configuration files, restart PostgreSQL to apply the new settings:
8. Check PostgreSQL Status:
To ensure that PostgreSQL is running and your changes have been applied successfully, check the service status:
sudo systemctl status postgresql # For Ubuntu/Debian
sudo systemctl status postgresql-13 # For CentOS/RHEL
You should see output indicating that PostgreSQL is active and running.
9. Exit PostgreSQL Command Line:
After completing the initial configuration, you can exit the PostgreSQL command-line interface by typing:
\q
Creating and Managing PostgreSQL Users
In PostgreSQL, users are essential for managing access and permissions to databases. You can create, modify, and delete users as needed. Here’s a step-by-step guide for creating and managing PostgreSQL users.
1. Create a New User:
To create a new user, you use the CREATE USER command. It’s important to assign a secure password when creating a user.
CREATE USER username WITH PASSWORD 'password';
Replace username with the desired username and password with a strong password for the user.
2. Granting Privileges to Users:
After creating a user, you need to grant them appropriate permissions to interact with the database. You can grant the user access to specific databases or allow them specific operations.
- Grant All Privileges on a Database: This command gives the user full access to a specific database.
GRANT ALL PRIVILEGES ON DATABASE my_database TO username;Replace
my_databasewith the name of the database andusernamewith the user’s name - Grant Specific Privileges: You can grant more specific permissions, such as the ability to only select data from a table:
GRANT SELECT ON my_table TO username;Replace
my_tablewith the table name andusernamewith the user.
3. Modify an Existing User:
You can alter an existing user’s properties, such as their password, login privileges, or membership in roles.
- Change a User’s Password: To change the password of an existing user:
ALTER USER username WITH PASSWORD 'new_password';Grant Login Privileges: You can allow or disallow a user’s ability to log in by altering their properties. For example, to disable login for a user:
ALTER USER username NOLOGIN;To allow the user to log in again:
ALTER USER username LOGIN;
4. Managing User Roles:
In PostgreSQL, roles can be used to group users together. You can create roles and assign them to users to manage their permissions more easily.
- Create a New Role: You can create roles that group users with similar permissions.
CREATE ROLE role_name;Grant Role to a User: Once a role is created, you can grant it to a user, which gives the user the permissions associated with that role.
GRANT role_name TO username; - Revoke a Role from a User: To revoke a role from a user, use the following command:
REVOKE role_name FROM username;
5. Listing Users and Roles:
You can list all users and roles in PostgreSQL by querying the system catalog.
\du
This command will display a list of all roles and their associated attributes.
6. Delete a User:
If you no longer need a user, you can remove them from the PostgreSQL system.
DROP USER username;
Replace username with the name of the user you want to delete. Make sure that the user does not own any objects in the database or transfer ownership before deleting the user.
7. Reassigning Objects Owned by a User:
If you need to delete a user but that user owns objects in the database (like tables or schemas), you must first reassign those objects to another user:
REASSIGN OWNED BY username TO new_owner;
Replace username with the user whose objects you want to reassign and new_owner with the user who will take ownership of the objects.
Setting Up Backups and Restoring PostgreSQL Databases
Backing up your PostgreSQL database is critical to ensure that your data is safe in case of a failure or corruption. Restoring backups allows you to recover the database to a previous state. Here’s how to set up backups and restore PostgreSQL databases.
1. Using pg_dump to Backup a PostgreSQL Database:
The pg_dump utility is used to create backups of a PostgreSQL database. It can back up a single database or all databases, and it supports multiple formats, such as plain SQL, custom, or directory format.
- Backing Up a Single Database:To create a backup of a single database, use the following command:
pg_dump my_database > my_database_backup.sqlReplace
my_databasewith the name of your database. This will create a plain SQL backup file (my_database_backup.sql) that contains the SQL statements necessary to recreate the database. - Backing Up All Databases:If you want to back up all databases on the PostgreSQL server, use the
pg_dumpallcommand:pg_dumpall > all_databases_backup.sqlThis command will create a backup of all databases in a plain SQL format.
- Backing Up in Custom Format:To back up in a custom format (which allows for more flexibility when restoring), use the
-Fcflag:pg_dump -Fc my_database > my_database_backup.dumpThis command creates a compressed backup file that can be restored using the
pg_restoreutility.
2. Automating Backups with Cron:
To automate backups on a regular schedule, you can use cron jobs. This allows you to set up periodic backups without manual intervention.
- Edit the Crontab File:To edit the crontab for the PostgreSQL user, run the following command:
crontab -e - Set Up a Backup Schedule:Add a cron job to schedule backups. For example, to back up a database every day at midnight, add the following line to the crontab:
0 0 * * * pg_dump my_database > /path/to/backup/my_database_backup_$(date +\%F).sqlThis command will create a backup of
my_databaseat midnight every day, with the filename including the current date (YYYY-MM-DDformat).
3. Restoring a PostgreSQL Database from a Backup:
Restoring from a backup is just as simple as creating one. The method you use depends on the format of the backup.
- Restoring from a Plain SQL Backup:If you have a plain SQL backup, you can restore it using the
psqlcommand:psql my_database < my_database_backup.sqlReplace
my_databasewith the name of the database you want to restore to, andmy_database_backup.sqlwith the path to your backup file.
- Restoring from a Custom Format Backup:If you backed up using the custom format (e.g., with
pg_dump -Fc), you can restore usingpg_restore:pg_restore -d my_database my_database_backup.dumpReplace
my_databasewith the name of the database to restore to andmy_database_backup.dumpwith your custom-format backup file. - Restoring All Databases from a Backup:If you used
pg_dumpallto back up all databases, you can restore all databases with the following command:psql -f all_databases_backup.sql postgresThis will restore all databases from the backup file
all_databases_backup.sql.
4. Verifying Backups:
It is important to verify that your backups are valid and can be restored. You can verify a backup by restoring it to a test database and checking its integrity.
- Restore to a Test Database:Create a new test database and restore the backup to this database:
createdb test_database psql test_database < my_database_backup.sql - Verify the Restored Data:After restoring, check the data to ensure it is complete and consistent with the original database.
5. Backing Up Configuration Files:
In addition to the database data itself, it is also important to back up PostgreSQL’s configuration files, which include postgresql.conf and pg_hba.conf. These files are typically located in the data directory (/var/lib/postgresql/12/main for Ubuntu or /var/lib/pgsql/12/data for CentOS/RHEL).
You can back them up using the following command:
cp /path/to/postgresql.conf /path/to/backup/postgresql.conf.bak
cp /path/to/pg_hba.conf /path/to/backup/pg_hba.conf.bak