Tutorial

How To Install and Use PostgreSQL on Ubuntu 18.04

How To Install and Use PostgreSQL on Ubuntu 18.04
Not using Ubuntu 18.04?Choose a different version or distribution.
Ubuntu 18.04

Introduction

Relational database management systems are a key component of many web sites and applications. They provide a structured way to store, organize, and access information.

PostgreSQL, or Postgres, is a relational database management system that provides an implementation of the SQL querying language. It is a popular choice for many small and large projects and has the advantage of being standards-compliant and having many advanced features like reliable transactions and concurrency without read locks.

This guide demonstrates how to install Postgres on an Ubuntu 18.04 VPS instance and also provides instructions for basic database administration.

Prerequisites

To follow along with this tutorial, you will need one Ubuntu 18.04 server that has been configured by following our Initial Server Setup for Ubuntu 18.04 guide. After completing this prerequisite tutorial, your server should have a non-root user with sudo permissions and a basic firewall.

Step 1 — Installing PostgreSQL

Ubuntu’s default repositories contain Postgres packages, so you can install these using the apt packaging system.

Since this is your first time using apt in this session, refresh your local package index. Then, install the Postgres package along with a -contrib package that adds some additional utilities and functionality:

  1. sudo apt update
  2. sudo apt install postgresql postgresql-contrib

Ensure that the server is running using the systemctl start command:

  1. sudo systemctl start postgresql.service

Now that the software is installed and running, we can go over how it works and how it may be different from similar database management systems you may have used.

Step 2 — Using PostgreSQL Roles and Databases

By default, Postgres uses a concept known as roles to handle authentication and authorization. These are, in some ways, similar to regular Unix-style accounts, but Postgres does not distinguish between users and groups and instead prefers the more flexible term “role”.

Upon installation, Postgres is set up to use ident authentication, meaning that it associates Postgres roles with a matching Unix/Linux system account. If a role exists within Postgres, a Unix/Linux username with the same name is able to sign in as that role.

The installation procedure created a user account called postgres that is associated with the default Postgres role. In order to use Postgres, you can log into that account.

There are a few ways to use this account to access Postgres.

Switching Over to the postgres Account

Switch over to the postgres account on your server by typing:

  1. sudo -i -u postgres

You can now access a Postgres prompt immediately by typing:

  1. psql

This will log you into the PostgreSQL prompt, and from here you are free to interact with the database management system right away.

Exit out of the PostgreSQL prompt by typing:

  1. \q

This will bring you back to the postgres Linux command prompt.

Accessing a Postgres Prompt Without Switching Accounts

In the last example, you were instructed to get to the Postgres prompt by first switching to the postgres user and then running psql to open the Postgres prompt. You could alternatively do this in one step by running the single command psql as the postgres user with sudo, like this:

  1. sudo -u postgres psql

This will log you directly into Postgres without the intermediary bash shell in between.

Again, you can exit the interactive Postgres session by typing:

  1. \q

Many use cases require more than one Postgres role. Read on to learn how to configure these.

Step 3 — Creating a New Role

Currently, you just have the postgres role configured within the database. You can create new roles from the command line with the createrole command. The --interactive flag will prompt you for the name of the new role and also ask whether it should have superuser permissions.

If you are logged in as the postgres account, you can create a new user by typing:

  1. createuser --interactive

If, instead, you prefer to use sudo for each command without switching from your normal account, type:

  1. sudo -u postgres createuser --interactive

The script will prompt you with some choices and, based on your responses, execute the correct Postgres commands to create a user that meets your specifications.

First, the prompt will ask you to specify a name for the new role. The following example names the role sammy but you can name yours whatever you like:

Output
Enter name of role to add: sammy

Next, you’ll be asked if the new role should be a superuser. In PostgreSQL, a superuser role has extremely broad privileges and they can bypass nearly all permission checks.

The following example specifies that the sammy role should be a superuser but, because superuser roles have a great deal of power and control over a database, you should not grant new roles superuser status lightly:

Output
Enter name of role to add: sammy Shall the new role be a superuser? (y/n) y

Note that you can only create new superuser roles if you are creating them as a role that is already a superuser. By default, the postgres role is a superuser.

You can get more control by passing some additional flags. Check out the options by looking at the man page:

  1. man createuser

Your installation of Postgres now has a new role, but you have not yet added any databases. The next section describes this process.

Step 4 — Creating a New Database

Another assumption that the Postgres authentication system makes by default is that for any role used to log in, that role will have a database with the same name which it can access.

This means that, if the user you created in the last section is called sammy, that role will attempt to connect to a database which is also called “sammy” by default. You can create the appropriate database with the createdb command.

If you are logged in as the postgres account, you would type something like:

  1. createdb sammy

If, instead, you prefer to use sudo for each command without switching from your normal account, you would type:

  1. sudo -u postgres createdb sammy

This flexibility provides multiple paths for creating databases as needed.

Step 5 — Opening a Postgres Prompt with the New Role

To log in with ident based authentication, you’ll need a Linux user with the same name as your Postgres role and database.

If you don’t have a matching Linux user available, you can create one with the adduser command. You will have to do this from your non-root account with sudo privileges (meaning, not logged in as the postgres user):

  1. sudo adduser sammy

Once this new account is available, you can either switch over and connect to the database by typing:

  1. sudo -i -u sammy
  2. psql

Or, you can do this inline:

  1. sudo -u sammy psql

This command will log you in automatically, assuming that all of the components have been properly configured.

If you want your user to connect to a different database, you can do so by specifying the database like this:

  1. psql -d postgres

Once logged in, you can get check your current connection information by typing:

  1. \conninfo
Output
You are connected to database "sammy" as user "sammy" via socket in "/var/run/postgresql" at port "5432".

This is useful if you are connecting to non-default databases or with non-default users.

Step 6 — Creating and Deleting Tables

Now that you know how to connect to the PostgreSQL database system, you can learn some basic Postgres management tasks.

First, create a table to store some data. As an example, a table that describes some playground equipment.

The basic syntax for this command is as follows:

CREATE TABLE table_name (
    column_name1 col_type (field_length) column_constraints,
    column_name2 col_type (field_length),
    column_name3 col_type (field_length)
);

These commands give the table a name, and then define the columns as well as the column type and the max length of the field data. You can also optionally add table constraints for each column.

You can learn more about how to create and manage tables in Postgres here.

For demonstration purposes, create a sample table like this:

  1. CREATE TABLE playground (
  2. equip_id serial PRIMARY KEY,
  3. type varchar (50) NOT NULL,
  4. color varchar (25) NOT NULL,
  5. location varchar(25) check (location in ('north', 'south', 'west', 'east', 'northeast', 'southeast', 'southwest', 'northwest')),
  6. install_date date
  7. );

These commands will create a table that inventories playground equipment. This starts with an equipment ID, which is of the serial type. This data type is an auto-incrementing integer. You’ve also given this column the constraint of primary key which means that the values must be unique and not null.

For two of the columns (equip_id and install_date), the commands do not specify a field length. This is because some column types don’t require a set length because the length is implied by the type.

The next two commands create columns for the equipment type and color respectively, each of which cannot be empty (as specified by the NOT NULL constraint applied to each). The line after these creates a location column and adds a constraint requiring this column’s values to be one of eight possible values. The last line within the parentheses creates a date column that records the date on which you installed the equipment.

Note that in SQL, every statement must end in a semicolon (;).

If you entered the CREATE TABLE operation correctly, it will return this output:

Output
CREATE TABLE

You can find a list of tables within this database by typing:

  1. \d
Output
List of relations Schema | Name | Type | Owner --------+-------------------------+----------+------- public | playground | table | sammy public | playground_equip_id_seq | sequence | sammy (2 rows)

Your playground table is here, but there’s also something called playground_equip_id_seq that is of the type sequence. This is a representation of the serial type which you gave your equip_id column. This keeps track of the next number in the sequence and is created automatically for columns of this type.

If you only want the table returned without the sequence, you can type:

  1. \dt
Output
List of relations Schema | Name | Type | Owner --------+------------+-------+------- public | playground | table | sammy (1 row)

Step 7 — Adding, Querying, and Deleting Data in a Table

Now that you have a table, you can insert some data into it.

As an example, add a slide and a swing by calling the table you want to add to, naming the columns and then providing data for each column, like this:

  1. INSERT INTO playground (type, color, location, install_date) VALUES ('slide', 'blue', 'south', '2017-04-28');
  2. INSERT INTO playground (type, color, location, install_date) VALUES ('swing', 'yellow', 'northwest', '2018-08-16');

You should take care when entering the data to avoid a few common hangups. For one, do not wrap the column names in quotation marks, but the column values that you enter do need quotes.

Another thing to keep in mind is that you do not enter a value for the equip_id column. This is because this is automatically generated whenever a new row in the table is created.

Retrieve the information you’ve added by typing:

  1. SELECT * FROM playground;
Output
equip_id | type | color | location | install_date ----------+-------+--------+-----------+-------------- 1 | slide | blue | south | 2017-04-28 2 | swing | yellow | northwest | 2018-08-16 (2 rows)

This output indicates that your equip_id has been filled in successfully and that all of your other data has been organized correctly.

If the slide on the playground breaks and you have to remove it, you can also remove the row from your table by typing:

  1. DELETE FROM playground WHERE type = 'slide';

Query the table again:

  1. SELECT * FROM playground;
Output
equip_id | type | color | location | install_date ----------+-------+--------+-----------+-------------- 2 | swing | yellow | northwest | 2018-08-16 (1 row)

Notice that your slide is no longer a part of the table.

Step 8 — Adding and Deleting Columns from a Table

After creating a table, you can modify it to add or remove columns relatively easily. Add a column to show the last maintenance visit for each piece of equipment by typing:

  1. ALTER TABLE playground ADD last_maint date;

The next time you view your table information again, the new column will have been added (but no data will have been entered):

  1. SELECT * FROM playground;
Output
equip_id | type | color | location | install_date | last_maint ----------+-------+--------+-----------+--------------+------------ 2 | swing | yellow | northwest | 2018-08-16 | (1 row)

To delete a column, you can enter an SQL statement very similar to the one you used to add the last_maint column. If you find that your work crew uses a separate tool to keep track of maintenance history, you can delete of the column by typing:

  1. ALTER TABLE playground DROP last_maint;

This deletes the last_maint column and any values found within it, but leaves all the other data intact.

Step 9 — Updating Data in a Table

So far, you’ve learned how to add records to a table and how to delete them, but this tutorial hasn’t yet covered how to modify existing entries.

You can update the values of an existing entry by querying for the record you want and setting the column to the value you wish to use. You can query for the “swing” record (this will match every swing in your table) and change its color to “red”. This could be useful if you gave the swing set a paint job:

  1. UPDATE playground SET color = 'red' WHERE type = 'swing';

You can verify that the operation was successful by querying the data again:

  1. SELECT * FROM playground;
Output
equip_id | type | color | location | install_date ----------+-------+-------+-----------+-------------- 2 | swing | red | northwest | 2010-08-16 (1 row)

As this output indicates, your slide is now registered as being red.

Conclusion

You are now set up with PostgreSQL on your Ubuntu 18.04 server. However, there is still much more to learn with Postgres. Here are some more guides that cover how to use Postgres:

Want to launch a high-availability PostgreSQL cluster in a few clicks? DigitalOcean offers worry-free PostgreSQL managed database hosting. We’ll handle maintenance and updates and even help you migrate your database from external servers, cloud providers, or self-hosted solutions. Leave the complexity to us, so you can focus on building a great application.

Learn more here

About the author(s)

Justin Ellingwood
Justin Ellingwood
See author profile
Mark Drake
Mark DrakeManager, Developer Education
See author profile

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
17 Comments
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Thanks. Useful article

Hello guys can you add how to set up the postgres to allow authorized user to connect from postgres clients such as pgadmin . inshort allow remote access. because once we have access then its easy to manage database . then you dont always need the sql cmds . also we can directly connect our apps

Mark Drake
DigitalOcean Employee
DigitalOcean Employee badge
August 3, 2018

Hello @RegalarTech, thank you so much for your comment. We really appreciate your suggestion for a new tutorial topic and are currently scoping out how we can best execute it. We’ll keep you posted!

Hello @mdrake,

Thanks for the tutorial. I will like to find out if there is an update on @RegalarTech’s request pls.

Br, Stephen

Mark Drake
DigitalOcean Employee
DigitalOcean Employee badge
October 25, 2018

Hi @nasowah, and hello again @RegalarTech! We recently published this guide on How To Install and Configure pgAdmin 4 in Server Mode. If you have any thoughts or suggestions for that guide, please share them in the comments section of that tutorial.

Thank you very much! The post was really helpful.

@mdrake Thanks for the detailed step by step guide, I hope it will help many and really appreciate that DigitalOcean takes serious efforts for requests. cheers.

After this line sudo adduser sammy it ask me for Postgres password. What password is expected? Anything I add at this line it says “Sorry try again” and after three attends it says sudo: 3 incorrect password attempts

It’s should be Ubuntu user password (sudoer), Not postgres password

In psql change the password:

ALTER USER postgres WITH PASSWORD 'password';

I don’t know my postgresql password install i can not connection it

alexdo
Site Moderator
Site Moderator badge
December 13, 2024

If you’re unable to connect to PostgreSQL because you don’t know the postgres user’s password, you can reset it or configure the server to temporarily allow a connection without a password. Here’s how you can fix the issue on Ubuntu:


Steps to Reset the postgres User Password:

  1. Switch to the postgres User:
sudo -u postgres psql

This command switches to the postgres system user and launches the PostgreSQL shell. No password is required because this is done as a system-level user.

  1. Set a New Password: In the PostgreSQL shell, run:
ALTER USER postgres PASSWORD 'yournewpassword';

Replace yournewpassword with a secure password of your choice.

  1. Exit the PostgreSQL Shell: Type:
\q
  1. Reconnect with the New Password: Now you can connect using the new password:
psql -U postgres -W

When prompted, enter the new password.

Hi, following this tutorial I created a video tutorial and posted it on YouTube. I entered the configuration part also for PostGIS. The video is in Italian, but the English subtitles work discreetly https://youtu.be/NvM09ken26o

alexdo
Site Moderator
Site Moderator badge
December 13, 2024

Thanks for sharing this with the community! Hopefully the video will reach everyone who needs the extra help!

Regards

Hello, I am trying to deploy my rails app on digital ocean. and am following this article https://gorails.com/deploy/ubuntu/18.04 but when i am trying to run this command sudo apt-get install postgresql postgresql-contrib libpq-dev it is showing the following errors.

Building dependency tree       
Reading state information... Done
libpq-dev is already the newest version (11.2-1.pgdg16.04+1).
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 postgresql : Depends: postgresql-11 but it is not going to be installed
 postgresql-contrib : Depends: postgresql-contrib-11
E: Unable to correct problems, you have held broken packages.```

What is the problem an what should i do.

[I am workign with my new user, not in root user]

Thank you
alexdo
Site Moderator
Site Moderator badge
December 13, 2024

The error indicates there are unmet dependencies for the postgresql and postgresql-contrib packages. This typically happens when the package manager encounters conflicts between the package versions available in the repository and the versions currently installed or required.

Regards

Hi, I ran into a bundle install issue where I couldn’t install my PG gem.

I had to run “sudo apt-get install libpq-dev” to get the right packages. Hope this helps anyone that may be stuck on installing the pg gem.

alexdo
Site Moderator
Site Moderator badge
December 13, 2024

Heya,

The libpq-dev libpq-dev is great addition. If you want to use the pg gem for Rails you will need the libq-dev package. When you run bundle install, it uses libpq for database connectivity. Without libpq-dev, the build process fails because the necessary headers (libpq-fe.h, etc.) are missing.

Basically for basic usage of PostgreSQL, such as running the server or using psql, the libpq-dev package is not required.

It’s mainly needed for development environments or building software that depends on PostgreSQL.

Regards

Hey guys. This tutorial does not describe how to add postgres user to the sudoers file. It seems it should be added right before the ‘Accessing a Postgres Prompt Without Switching Accounts’ section as I was unable to do this step or beyond. Thanks!

alexdo
Site Moderator
Site Moderator badge
December 13, 2024

Heya,

Here’s how to add the postgres user to the sudoers file:

Adding postgres to the sudoers File:

  1. Edit the sudoers file safely using visudo:
sudo visudo
  1. Add the postgres user with the necessary privileges: Scroll down to the section where other user privileges are defined (usually towards the end) and add the following line:
postgres ALL=(ALL) NOPASSWD:ALL
  • ALL=(ALL) NOPASSWD:ALL allows the postgres user to execute any command as any user without entering a password.
  1. Save and exit:
  • In visudo, press Ctrl+O to save and Ctrl+X to exit.
  1. Verify the changes: You can test it by running a command with sudo as the postgres user:
sudo -u postgres whoami

This should output postgres without prompting for a password.

After using the below command:

$ sudo apt install postgresql postgresql-contrib

Success. You can now start the database server using:

/usr/lib/postgresql/10/bin/pg_ctl -D /var/lib/postgresql/10/main -l logfile start

Ver Cluster Port Status Owner Data directory Log file 10 main 5432 down postgres /var/lib/postgresql/10/main /var/log/postgresql/postgresql-10-main.log update-alternatives: using /usr/share/postgresql/10/man/man1/postmaster.1.gz to provide /usr/share/man/man1/postmaster.1.gz (postmaster.1.gz) in auto mode Setting up postgresql (10+190ubuntu0.1) … Setting up postgresql-contrib (10+190ubuntu0.1) … Processing triggers for systemd (237-3ubuntu10.29) … Processing triggers for ureadahead (0.100.0-20) …

Why the status shows down?

alexdo
Site Moderator
Site Moderator badge
December 13, 2024

The status shows “down” because the PostgreSQL service is not automatically started after installation. Here’s how you can resolve it and start the PostgreSQL service:

Steps to Start PostgreSQL:

  1. Start the PostgreSQL Service: Run the following command to start the PostgreSQL server:
sudo systemctl start postgresql
  1. Enable the Service at Boot (Optional): To ensure PostgreSQL starts automatically when the system boots, use:
sudo systemctl enable postgresql
  1. Check the Status of PostgreSQL: Verify that the PostgreSQL service is running:
sudo systemctl status postgresql

You should see a message indicating that the service is “active (running).”

Will these instructions work for Postgresql 9.6 ? We use that version at work so that is what I have to install. Thanks for the tutorial.

alexdo
Site Moderator
Site Moderator badge
December 31, 2024

Heya,

PostgreSQL 9.6 is an older version and isn’t available in those default repositories.

You can still install and use PostgreSQL 9.6 on Ubuntu 18.04 by following these steps:

Since PostgreSQL 9.6 is not in the default repositories for Ubuntu 18.04, you’ll need to add the PostgreSQL APT repository:

sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ bionic-pgdg main" > /etc/apt/sources.list.d/pgdg.list' wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add - sudo apt update

You can use the following command to install PostgreSQL 9.6:

sudo apt install postgresql-9.6 postgresql-contrib-9.6

Ensure the PostgreSQL service is running and enabled at startup:

sudo systemctl start postgresql 
sudo systemctl enable postgresql

Once PostgreSQL 9.6 is installed, you can follow most of the instructions in the tutorial, such as managing roles, creating databases, and configuring authentication. Keep in mind:

PostgreSQL 9.6 doesn’t support some features introduced in later versions. You should use commands specific to PostgreSQL 9.6 for any version-dependent configurations.

Regards

Thank you for this amazing article. I was always wonder why my “$psql” commands don’t work(due to absence of “ident” auth) and some other stuff like best way to create new user and databases etc.

Precise, to the point and in-depth article. Gonna recommend everyone.

Step 5 is very hard to understand. I don’t understand if I am supposed to be in my linux user or postgres user

I’m trying to login with my adrian role

psql -d postgres -U adrian

but I get “Peer authentication failed for user adrian”

This article had what I needed: https://www.digitalocean.com/community/tutorials/how-to-use-roles-and-manage-grant-permissions-in-postgresql-on-a-vps--2

The article is very useful. Thank you.

make it $ sudo apt-get install postgresql postgresql-contrib libpq-dev

alexdo
Site Moderator
Site Moderator badge
December 13, 2024

Heya,

The libpq-dev libpq-dev is great addition. For basic usage of PostgreSQL, such as running the server or using psql, the libpq-dev package is not required.

It’s mainly needed for development environments or building software that depends on PostgreSQL.

Regards

Great article. Useful article. Thank you.

Hi Digital Ocean Team,

I am trying to create a scripted installation of Postgres on Ubuntu 18.04.06, using bash. In order to do this, I am using the following your post above as a starting point.

The account that I am using is a sudoer on the machine. I am running the following two lines - the problem occurs on the second line:

sudo apt-get -y update sudo apt-get -y install postgresql

The apt update completes successfully, then the postgresql install chugs along until it reaches this point:

Selecting previously unselected package postgresql. Preparing to unpack …/postgresql_14+238.pgdg18.04+1_all.deb … Unpacking postgresql (14+238.pgdg18.04+1) … Setting up postgresql-client-common (238.pgdg18.04+1) … Setting up postgresql-common (238.pgdg18.04+1) … Password:

I have tried entering the password to my sudoer account - all it does is hang. I have also tried just hitting ENTER - this hangs too.

I can see from your post and the /etc/passwd file that the Postgres install process creates a postgres unix account automatically. If the Password: prompt is asking for the password to this postgres account, I don’t know where to find this password either.

To summarize:

  • Can this Password: prompt be avoided entirely?
  • If the prompt can’t be avoided, where do I find the correct password?

Thanks !

alexdo
Site Moderator
Site Moderator badge
December 13, 2024

The issue you’re experiencing is related to how the postgresql package setup invokes the adduser command to create the postgres system user during installation. By default, the installation script might prompt for a password if the system configuration doesn’t align with the expected automation behavior

To avoid the password prompt entirely, you can preconfigure the system and use the DEBIAN_FRONTEND=noninteractive environment variable. This ensures that the package installation process runs without any interactive prompts.

Regards

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.