Skip to main content

Setting up a remote Postgres database server on Ubuntu 18.04

Introduction

Postgres is a powerful relational database management system, it can handle large workloads from a single machine to that of a data center. It is highly scalable and widely popular. In this article, we will be learning how to set up a remote Postgres database server to use for your projects. This article setup will allow Postgres connection from any IP address and will not cover specific/authorized IP connection.

Prerequisites

  • Familiarity with the command line interface
  • An Ubuntu server, you can quickly provision one from DigitialOcean or any cloud provider
  • A lot of patience
  • Postgres installed on a local machine

Installing Postgres

In this step, you will be installing Postgres on your server. The first thing to do is SSH into your server by running:
ssh server_user@server_ip
Note:
server_user is your server user you would like to log in with
server_ip is the IP address of your server
Then input your relevant user password or SSH key password if any. Next, update your server packages and dependencies by running:
sudo apt-get update
When that is done, install Postgres by running:
sudo apt-get install postgresql postgresql-contrib
This will install Postgres along with its associated dependencies. When the process is complete, switch the user to postgres to be able to execute Postgres commands with Postgres default user by running:
su - postgres
The server user will be switched from root to postgres. You can access the Postgres shell by running:
psql
You will be shown something similar to this:
postgres@logrocket:~$ psql
psql (10.12 (Ubuntu 10.12-0ubuntu0.18.04.1))
Type "help" for help
postgres=#

Create user

In this step, you will be creating a new user that will be used to access your Postgres database remotely. To create a new user, exit the Postgres shell by executing:
\q
While still being logged in as postgres run the following command to create a new user:
createuser --interactive --pwprompt
A prompt will be shown to you asking you to input your desired user role, name, password, and if you want the user to be a superuser. Here is an example:
Enter name of role to add: cleopatra
Enter password for new role:
Enter it again:
Shall the new role be a superuser? (y/n) y
I named my user role cleopatra and I made my user a superuser. A superuser is a user that has all the privileges available on a Postgres instance. Next, we will be assigning cleopatra to a database. To do this, run the following command:
createdb -O cleopatra egypt
This command above will create a new database named egyptand assign cleopatra to be the database user.

Allow remote access

In this step, we will look at how to configure Postgres to accept external connections. To begin, open the configuration file with your preferred editor:
nano /etc/postgresql/10/main/postgresql.conf
Look for this line in the file:
#listen_addresses = 'localhost'
Uncomment, and change the value to '*', this will allow Postgres connections from anyone.
listen_addresses = '*'
Save and exit the file. Next, modify pg_hba.conf to also allow connections from everyone. Open the file with your preferred editor:
nano /etc/postgresql/10/main/pg_hba.conf
Modify this section:
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
To this:
# IPv4 local connections:
host    all             all             0.0.0.0/0            md5
This file stores the client authentication, each record specifies an IP address range, database name, username, and authentication method. In our case, we are granting all database users access to all databases with any IP address range, thus, letting any IP address connect. Save and exit the file. Next, allow port 5432through the firewall by executing:
sudo ufw allow 5432/tcp
Finally, restart Postgres to apply all the changes you have made to its configuration by running:
sudo systemctl restart postgresql

Connect to Postgres remotely

In this step, you will be connecting to your server from an external machine. Connect to the remote Postgres database by running:
psql -h {server_ip} -d egypt -U cleopatra
Where {server_ip} is your server IP address, you will get a prompt to type your user password, if the credentials match you’ll be logged into the Postgres shell for cleopatra and database egypt.
login cli
Create a new table and name it pharaohs by executing the following in the Postgres shell:
create table pharaohs(name text);
create database
Next, add a record to the pharaohs table, you will be adding Tutankhamun as a string to the table by running the following in the Postgres shell:
insert into pharaohs (name) values ('Tutankhamun');
add record
Next, we will be accessing our database using a GUI (Graphical User Interface) tool like tablePlus which enables you to visualize data away from the command line interface to see if we can find the records we created. Open TablePlus and click on Create a newconnection.
Open TablePlus
Select Postgres from the dropdown
dropdown of database options
Input credentials
Note:
Postgres default port is 5432
Ignore the SSL regions (we won’t cover this topic in this post)
Input credentialsIf your credentials are correct, you will be shown a GUI panel to view your database records in which you will find the table created and the record we added to it.
View records
As shown in the image, we can see the pharaohs table we created earlier and the record we added to it. Our remote database is ready!

Conclusion

We have seen how to configure a Postgres database server for remote access. With this knowledge, you can set up a database server for your next project. In production, there are some security measures you will have to keep in mind. For example, only allowing the specified IP address and not allowing root access to your server, 

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...