PostgreSQL on EC2 (Ubuntu) in AWS

28th January, 2020

AWS RDS might be expensive at initial stage however EC2 is much more relatively cheaper. At the same time, RDS comes with several advantages and less maintenance. In this blog, we will cover how to set up a PostgreSQL instance in EC2 such that it can be used similar to RDS.

The steps are as follows:

  1. Log in to your AWS account.
  2. Go to EC2 dashboard and create security group with following inbound rules: 
    1. Custom TCP: 5432, Source: Anywhere (or specific IP for more security)
    2. SSH TCP:22, Source: Anywhere
  3. Initiate an EC2 instance (Ubuntu, for.eg. t2.medium) and include the created security group.
  4. Once created, SSH into the instance (take help of the Connect button in the EC2 dashboard).
  5. Run the following commands:
    sudo apt-get update && sudo apt-get -y upgrade
    sudo apt-get install postgresql postgresql-contrib​
  6.   Now PostgreSQL has been initiated, however it wil only listen to localhost, so we need to edit the configuration of the PostgreSQL.
  7. But first we need to change the password of the user postgres (default user)
    sudo -u postgres psql
    postgres=#\password​
  8. Now update configuration for remote access for clients.
    # Edit pg_hba.conf in vim
    sudo vim /etc/postgresql/10/main/pg_hba.conf
    
    # Near bottom of file after local rules, add rule (allows remote access):
    host    all             all             0.0.0.0/0               md5
    
    # save file​
    # Edit config in vim
    sudo vim /etc/postgresql/10/main/postgresql.conf
    
    # Change line 59 to listen to external requests:
    listen_address='*'
      
    # save file​
  9. The last step is to restart the PostgreSQL server.
    # Restart postgres server
    sudo /etc/init.d/postgresql restart​
  10. Now you may connect to the EC2 postgresql using the public DNS provided  and port 5432.
  11. Create database.
    $sudo su postgres
    $psql
    postgres=# CREATE DATABASE <database_name>;
    postgres=# CREATE USER <user> with encrypted password '<password>';
    postgres=# GRANT ALL PRIVILEGES ON DATABASE <database_name> TO <user>;​

Have fun :)