In this article, we will explain how to set up a remote Postgresql database server on Ubuntu 18.04.
Setting up a remote Postgresql server lets you host your database on a separate machine and connect to it from your application or another server. This improves scalability, security, and performance in distributed environments.
Prerequisites:
- A server running Ubuntu 18.04 with Postgresql installed
- Root or sudo access to the server
- A client machine or application with Postgresql client installed
- A static IP address for both the server and client (or resolvable hostname)
Follow the steps below to configure a remote Postgresql database server on Ubuntu 18.04.
- Install PostgreSQL (if not already installed)
sudo apt update sudo apt install postgresql postgresql-contrib
- Configure Postgresql to Accept Remote Connections
- Edit the Postgresql.conf file:
sudo nano /etc/postgresql/10/main/postgresql.conf
Locate the line:
#listen_addresses = 'localhost'
Change it to:
listen_addresses = '*'
This allows Postgresql to listen for connections on all interfaces.
- Configure Client Authentication in pg_hba.conf:
sudo nano /etc/postgresql/10/main/pg_hba.conf
Add the following line at the end (replace your-client-ip and your-database-name as needed):
host all all your-client-ip/32 md5 If you want to allow an entire subnet: host all all 192.168.1.0/24 md5
- Restart PostgreSQL
sudo systemctl restart postgresql
- Create a Postgresql User and Database
Switch to the postgres user:sudo -i -u postgres
Create a new user and database:
createuser your_username --pwprompt
createdb your_database_name –owner=your_username
Grant all privileges:psql GRANT ALL PRIVILEGES ON DATABASE your_database_name TO your_username; \q
- Allow Postgresql Port (5432) Through the Firewall
sudo ufw allow 5432/tcp sudo ufw reload
- Connect Remotely
From the client machine:psql -h your-server-ip -U your_username -d your_database_name
- Edit the Postgresql.conf file:
In this manner, you have effectively configured a remote Postgresql database server on Ubuntu 18.04. Always ensure that proper firewall rules and strong user credentials are in place to keep your database secure.
Planning your PostgreSQL setup? Learn How to decide the size of PostgreSQL databases and tables