Table of Contents
Introduction
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.
Prerequisites
- Install Docker
- (optional) Install docker-compose
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
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 is below
Using psql
command to connect the database
psql --host localhost --port 5432 --username devopsroles --dbname my-db
The output terminal is 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 is below
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
Link Youtube: Docker run PostgreSQL
Conclusion
You have to use Docker run PostgreSQL databases. I hope this will be helpful for you. Thank you for reading the DevopsRoles page!