PostgreSQL Installation and DB Creation on Ubuntu 16.04
This installation procedure is based on Ubuntu 16.04. For other versions, see the PostgreSQL download page.
Installation¶
- Create the file /etc/apt/sources.list.d/pgdg.list, and add a line for the repository
- Import the repository signing key, and update the package lists
- Ubuntu includes PostgreSQL by default. To install PostgreSQL on Ubuntu, use the apt-get (or other apt-driving) command
- The bin directory (
/usr/lib/postgresql/9.6/bin) of postgresql package contains all the necessary commands. Hence let's make the directory accessible from any where. - Edit
~/.profilefile to export postgresql bin directory. - Add the following two lines to export postgresql utility commands
- Activate the profile
- During the installation, PostgreSQL will create a default user to operate under. We will be using this user for some administrative purposes.
- Log in with the following command
- Do the same as #4
- Logout from this user
- Now we can execute the utility commands from the shell, even for the
postgresuser.
Setup User/Role and DB¶
-
Note: PostgreSQL assumes that when we log in, we will be using a username that matches our operating system username, and that we will be connecting to a database with the same name as well.
-
Switch to user postgres
- Run
psqlcommand to createpostgres's password. It doesn't have any default password. - Create a user/role for our brand new database, let's say
blogand give the user toLOGINandCREATEDBpermissions. Also make the userOWNERof the dbblog - Quit
psqlcommandline interface - Exit (logout) from this user (
postgres) - Now we can run
psqlcommand with that newly created user without switching to userpostgresThis will connect the command line interface to the new dbblogwith this useradminlogged in. Output should be something like the followings:
Creating Cluster Data Directory¶
initdbwill attempt to create the directory we specify if it does not already exist. Of course, this will fail if initdb does not have permissions to write in the parent directory. It's generally recommendable that the PostgreSQL user own not just the data directory but its parent directory as well, so that this should not be a problem. If the desired parent directory doesn't exist either, we will need to create it first, using root privileges if the grandparent directory isn't writable. So the process might look like this:- Again before running any postgresql commands we need to switch user to
postgres - Now we can point the directory for creating cluster data directory using
initdOutput should be ended with something like this: - So let's start the server