Ruan Bekker's Blog

From a Curious mind to Posts on Github

Create Users Databases and Granting Access for Users on PostgreSQL

Short tutorial on how to create databases on postgresql, creating users and granting permissions so that the users has access to the created database.

Create and Apply Permissions

Logon to postgresL

1
2
$ sudo -u postgres psql
psql=>

Create the database mydb:

1
psql=> create database mydb;

Create the user dba and assign a password:

1
psql=> create user concourse with encrypted password 'sekretpw';

Grant all privileges for the user on the database:

1
2
psql=> grant all privileges on database concourse1 to concourse;
psql=> \q

Allowing Remote Conenctions

If you want to allow remote connections, you would first need to change the config that the server listens on all interfaces:

1
2
# /etc/postgresql/10/main/postgresql.conf 
listen_addresses = '0.0.0.0'

We also the need to update the trust relationship, in this case we will only want one user to access one database from any source:

1
2
3
# /etc/postgresql/10/main/pg_hba.conf
# TYPE  DATABASE        USER            ADDRESS                 METHOD
hostnossl mydb        dba     0.0.0.0/0       trust

After the config is in place, restart the server:

1
$ /etc/init.d/postgresql restart

PostgreSQL Client

From a remote source, test the connection to your server:

1
2
3
4
5
6
$ psql --host postgres.example.com --username dba --dbname mydb --password
Password:
psql (11.1, server 10.5 (Ubuntu 10.5-1.pgdg16.04+1))
Type "help" for help.

mydb=>

Comments