How to Run PostgreSQL on Docker

PostgreSQL is an object-oriented relational database management system whose Docker Image is one of the most downloaded images on Docker Hub. Containerized PostgreSQL instances are popular due to the simplicity of their deployment. They also allow developers to devote a PostgreSQL container for each application instead of maintaining one centralized database.

This tutorial teaches you how to run PostgreSQL on a Docker container.

Tutorial on how to run PostgreSQL in a Docker container.

Prerequisites

  • Access to a command line/terminal window.
  • A user account with sudo privileges.
  • An existing Docker installation.

Should I Run PostgreSQL in Docker?

Running PostgreSQL in Docker is a flexible and convenient option for many use cases. A containerized PostgreSQL database brings the following benefits:

  • Portability. Containerized apps can run in many different environments.
  • Isolation. A Docker container is a self-sufficient, isolated environment that helps avoid app conflicts and dependency problems.
  • Simplicity. Deploying and managing PostgreSQL instances in Docker requires basic knowledge of Docker commands. Spinning and discarding new instances takes seconds, which is excellent for development and testing.
  • Version management. You can test multiple versions of PostgreSQL on the same machine and not worry about version conflicts.

Run PostgreSQL on Docker Containers

This guide presents two methods to run the PostgreSQL image from Docker's official repository.

The first method features Docker Compose, a tool for managing multi-container Docker applications. The second uses a single Docker command with all the necessary information to deploy a new PostgreSQL container.

Read the sections below to learn how to use both methods.

Method 1: Run Postgres Using Docker Compose

Installing PostgreSQL with Docker using Docker Compose involves creating a YAML file that contains deployment instructions and applying that file with the docker-compose command.

Note: To deploy a Postgres container using Docker Compose, you must install it on your system. For assistance, refer to our guides: Install Docker Compose on Ubuntu and Install Docker Compose on CentOS.

Follow the steps below to run a PostgreSQL container:

1. Create a new directory and move to it:

mkdir postgres && cd postgres

2. Create a new docker-compose.yml file with a text editor of your choice (in this example, we used nano):

nano docker-compose.yml

3. Add the following content to the docker-compose file:

version: '3.8'
services:
  db:
    image: postgres:latest
    restart: always
    ports:
    - 5432:5432
    environment:
    - POSTGRES_USER=postgres
    - POSTGRES_PASSWORD=postgres
    volumes:
    - db:/var/lib/postgresql/data
volumes:
  db:
    driver: local

The YAML configuration file defines the following parameters:

  • A db service built using the latest PostgreSQL image. You can also specify the PostgreSQL version to use, e.g., postgres:16.1.
  • The port on which the container communicates. 5432 is the default port number for PostgreSQL.
  • Environment variables for the username and password.
  • A storage volume.

When you finish editing, save and exit the file.

5. Run the container using the docker-compose up command with the -d option to put it into detach mode:

docker-compose up -d
Running a PostgreSQL Docker container with Docker Compose.

The -d option allows you to continue to run commands from the current shell.

6. Optionally, check the logs with the command:

docker-compose logs -f

To return to the shell, press CTRL+C.

7. Go inside the container:

docker exec -it [container-name] /bin/sh

An sh shell prompt appears.

8. Access the PostgreSQL database by running psql, the command-line interface for PostgreSQL:

psql --username postgress

The PostgreSQL instance is ready to accept commands.

The psql interface ready to accept commands.

Method 2: Run Postgres Using a Single Docker Command

You can download and run a Postgres container by specifying all the necessary information in one command.

1. Execute the command:

docker run --name [container_name] -e POSTGRES_PASSWORD=[your_password] -d postgres

The command tells Docker to run a new container under a particular container name, defines the Postgres password, and then downloads the latest Postgres release. If successful, the command output displays the container ID for the newly created container.

Running a PostgreSQL container in Docker using a CLI command.

2. Confirm your PostgreSQL container is running by prompting Docker to list all running containers:

docker ps

The container shows up on the list.

Listing running Docker containers.

Enter a Postgres container with the docker exec command using the container name and psql as the command-line interface.

docker exec -it [container-name] psql -U postgres

The example below connects to the postgresql-example container.

Command for connecting to Postgres in a Docker container.

Starting with PostgreSQL Containers

Once you connect to a database using the psql CLI, you can use PostgreSQL syntax to create and manage databases, schemas, and tables. The following steps show some of the most common operations in PostgreSQL.

1. Create a database with the following command:

create database [db-name];
Creating a database in PostgreSQL.

2. Type the following command to view all the running databases:

\l

The created database appears in the list.

Listing available databases in PostgreSQL.

3. To connect to the database as the postgres user, type:

\c [db-name]

The output confirms the connection and the prompt changes to the current database's name.

Connecting to a database in PostgreSQL.

4. With the database set up, the next step is to create a schema that helps you get a logical representation of the database structure:

create schema [db-schema-name];
Creating a schema in PostgreSQL.

5. Create a PostgreSQL table. Use the create table command and enter a table name, column names, and PostgreSQL data types for each column:

create table [table-name] ([column1] [data-type], [column2] [data-type]);

The following example creates a table called plants with two columns, plant and color, containing text data type.

Creating a table in PostgreSQL.

6. Insert values into the table by using the following syntax:

insert into [table-name] values ([column1-value], [column2-value]);

The example below inserts the values roses and red into the plants table:

Inserting values into a table in PostgreSQL.

7. Show the table by executing the command below:

select * from [table-name]
Showing table values in PostgreSQL.

8. Exit the Postgres container by typing the following command:

\q

Conclusion

This article featured two ways to run a PostgreSQL in a Docker container. Deploying PostgreSQL in a container is cost-efficient, supports CI/CD development, and streamlines deployment and application management.

If you want to learn more about PostgreSQL deployment, read our article on how to deploy PostgreSQL on Kubernetes. Besides PostgreSQL, you can also run MySQL and MongoDB on Docker.

Was this article helpful?
YesNo
Sofija Simic
Sofija Simic is an experienced Technical Writer. Alongside her educational background in teaching and writing, she has had a lifelong passion for information technology. She is committed to unscrambling confusing IT concepts and streamlining intricate software installations.
Next you should read
How to Connect to a PostgreSQL Database From Command Line in Linux
February 22, 2024

PostgreSQL is an open source relational database management system. In this tutorial learn how to connect to...
Read more
How to List All Users in a MySQL Database
September 18, 2024

This simple tutorial analyses the commands used to list all user accounts in MySQL. Learn about additional...
Read more
How to Fix MySQL 'Command Not Found'
April 11, 2024

The 'Command Not Found' error is a general error not only found in MYSQL. By learning how to deal with it...
Read more
PostgreSQL Vs MySQL: A Detailed Comparison
March 30, 2023

Explore the differences between the two most widely used database management systems. PostgreSQL and MySQL...
Read more