Table of Contents
#Introduction
In this tutorial, How to use Docker run PostgreSQL databases and connect to Postgres Databases.
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.
Prerequisites
- Install Docker
- (optional) Install docker-compose
Docker Run 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
Note:
- -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 as below

Using psql command to connect the database
psql --host localhost --port 5432 --username devopsroles --dbname my-db
The output terminal as below

Your database is currently empty. I will create a table as an example
CREATE TABLE sites (id SERIAL PRIMARY KEY, name VARCHAR(100));
INSERT INTO sites (name)
VALUES ('devopsroles.com'), ('huuphan.com');
I will run a command to query the table created.
SELECT * FROM sites;
The output terminal as below

Docker Manage data persistence
The problem, We stop and start the container with the command “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 store 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 as below

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