Docker run PostgreSQL: A Step-by-Step Guide


In this tutorial, you will learn how to use Docker to run PostgreSQL databases and connect to them.

  • PostgreSQL is a powerful, open-source object-relational database
  • Docker is an open platform that runs an application in an isolated environment called a container.


Docker Run PostgreSQL container

You have to use Docker to run PostgreSQL databases. Below is an example command to run a PostgreSQL container:

docker run --name my-postgres-db -p 9000:5432 -e POSTGRES_PASSWORD=123456789  -e POSTGRES_USER=devopsroles  -e POSTGRES_DB=my-db -d postgres:14


  • -p 9000:5432: Host port 9000 and Container port 5432
  • Image: postgres version 14
  • Container name: my-postgres-db
  • Environment variables to configure our database: POSTGRES_USER, POSTGRES_PASSWORD, and POSTGRES_DB

The output terminal is below

Docker run PostgreSQL

Using psql command to connect the database

psql --host localhost --port 5432 --username devopsroles --dbname my-db

The output terminal is below

Docker run PostgreSQL

Your database is currently empty. I will create a table as an example

INSERT INTO sites (name)
  VALUES (''), ('');

I will run a command to query the table created.

SELECT * FROM sites;

The output terminal is below

Docker run PostgreSQL

Docker Manage data persistence

The problem is that we stop and start the container with the commands “docker stop my-postgres-db” and “docker start my-postgres-db” when creating a new container will not allow us to access the database that you are created, as it was isolated in your container.

Create a new volume with the following command. The solution stores the database outside of the container

docker volume create my-postgres-db-db

You will stop and remove your current container and create a new one.

docker stop my-postgres-db
docker rm my-postgres-db
docker run --name my-postgres-db -p 5432:5432  -e POSTGRES_PASSWORD=123456789  -e POSTGRES_USER=devopsroles  -e POSTGRES_DB=my-db -v my-postgres-db-db:/var/lib/postgresql/data -d postgres:14

How to know where the database is stored on your computer

docker inspect my-postgres-db-db

The output terminal is below

Docker run PostgreSQL


You have to use Docker run PostgreSQL databases. I hope this will be helpful for you. Thank you for reading the DevopsRoles page!


About HuuPV

My name is Huu. I love technology, especially Devops Skill such as Docker, vagrant, git, and so forth. I like open-sources, so I created to share the knowledge I have acquired. My Job: IT system administrator. Hobbies: summoners war game, gossip.
View all posts by HuuPV →

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.