Install PostgreSQL Inside Docker Container in Linux

Install PostgreSQL Inside Docker Container in Linux

PostgreSQL is a cross-platform relational database that allows to access data using Structured Query Language (SQL). PostgreSQL is an open-source project that available under the PostgreSQL License.

This tutorial explains how to install PostgreSQL inside a Docker container in the Linux. Commands have been tested on Ubuntu.

Prepare environment

Make sure you have installed Docker in your system. If you are using Ubuntu, installation instructions can be found in the post.

Install PostgreSQL

  • Host network

Run the following command to create a container for PostgreSQL that uses host network:

docker run -d --name=postgresql --restart=always --network=host \
    -v /opt/postgresql/data:/var/lib/postgresql/data \
    -e POSTGRES_PASSWORD=pwd123 \
    postgres
  • User-defined bridge network

User-defined bridge network can be used for listening on different port. By default, PostgreSQL service is listening on port 5432. It can be changed with -p option.

docker network create app-net
docker run -d --name=postgresql --restart=always --network=app-net \
    -p 8080:5432 \
    -v /opt/postgresql/data:/var/lib/postgresql/data \
    -e POSTGRES_PASSWORD=pwd123 \
    postgres

Note: don't forget to change postgres superuser password.

Testing PostgreSQL

Use the following command to run the PostgreSQL client (psql) and get all databases available on the server:

docker exec -it postgresql psql -U postgres -l

Output example:

                                                List of databases
   Name    |  Owner   | Encoding |  Collate   |   Ctype    | ICU Locale | Locale Provider |   Access privileges
-----------+----------+----------+------------+------------+------------+-----------------+-----------------------
 postgres  | postgres | UTF8     | en_US.utf8 | en_US.utf8 |            | libc            |
 template0 | postgres | UTF8     | en_US.utf8 | en_US.utf8 |            | libc            | =c/postgres          +
           |          |          |            |            |            |                 | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.utf8 | en_US.utf8 |            | libc            | =c/postgres          +
           |          |          |            |            |            |                 | postgres=CTc/postgres
(3 rows)

Uninstall PostgreSQL

To completely remove PostgreSQL, remove its container:

docker rm --force postgresql

Remove PostgreSQL image:

docker rmi postgres

You can also remove PostgreSQL data:

sudo rm -rf /opt/postgresql

If a user-defined bridge network was created, you can delete it as follows:

docker network rm app-net

Leave a Comment

Cancel reply

Your email address will not be published.