Docker run PostgreSQL

#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

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

Docker run PostgreSQL

Using psql command to connect the database

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

The output terminal as below

Docker run PostgreSQL

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 run PostgreSQL

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

Docker run PostgreSQL

Conclusion

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

,

About HuuPV

My name is Huu. I love technology and especially Devops Skill such as Docker, vagrant, git so forth. I likes open-sources. so I created DevopsRoles.com site to share the knowledge that I have learned. 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 *

Comment moderation is enabled. Your comment may take some time to appear.

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