Tag Archives: postgresql

Install PostgreSQL on Ubuntu for Rails developers

These instructions worked for Ubuntu 12-14.

Check the language in the system:

env | grep LC_

It should be “en_US.UTF-8”, if not you can configure in “System Setting > Language Support”.
Installing DDBB and libpq-dev to compile rails gem when bundling, with following command:

sudo apt-get install postgresql libpq-dev

To gain access from the server it-self, In /etc/postgresql/9.3/main/postgresql.conf, uncomment the following line:

listen_addresses = 'localhost'

To have access from rails app, modify the following line in /etc/postgresql/9.1/main/pg_hba.conf:

# "local" is for Unix domain socket connections only
local   all             all                                     md5

Restart the service:

sudo service postgresql restart

You will need to add a role:

sudo -u postgres psql
create role pg_user with createdb login password 'pg_user';

Be sure that your Gemfile includes: gem ‘pg’
Create your database.yml for dev and test:

common: &common
  adapter: postgresql
  username: pg_user
  password: pg_user

Create and fill the database:

rake db:create
rake db:migrate
rake db:seed

Some Postgre useful commands are:

  • List of databases: sudo -u postgres psql -l
  • Check server encoding: sudo -u postgres psql -c “SHOW SERVER_ENCODING”

PostgreSQL Backup/Restore

Continuing my notes publishing … How to backup/restore your PostgreSQL databases? when you recently get the responsibility of a web app? or you will renew your development environment? or you want to reproduce a production error in your machine? or you want to sleep better at night 😉 ? or ….? whatever.

Before to do anything always we should log as postgres user:

sudo su - postgres

Then backup one database:

pg_dump database_name > /tmp/database_name.bak

Or backup them all:

pg_dumpall > /tmp/backup_all.bak

After that you probably want to download them from server to your machine:

scp your.server.com:/tmp/backup_all.bak .

And finally you want to restore one database, but you will need to create the database previously:

createdb -T template0 database_name
psql database_name < database_name.bak

Maybe you also need to create a user and give it proper permissions:

create role user_name with createdb login password 'user_password';

Or restore them all:

psql -f backup_all.bak postgres

This will create all databases and users for you.