Steps to Persist Data In A Dockerized Postgres Using Volumes
Step 1: Create a docker volume. This volume will help in persisting the data.
docker volume create postgres_volume
Step 2: Run a Postgres docker container using docker volume.
docker run -d \
--name postgres \
-e POSTGRES_PASSWORD=gfg \
-v postgres_volume:/var/lib/postgresql/data \
postgres:latest
Step 3: Go inside the docker container.
docker exec -it postgres psql -U postgres
Step 4: Create a database.
CREATE DATABASE demo_db;
Step 5: Try to connect the database.
\c demo_db
Step 6: Create a table inside the database and insert some demo data . Then exit.
CREATE TABLE gfg_articles (id SERIAL PRIMARY KEY, name VARCHAR(255));
INSERT INTO gfg_articles (name) VALUES ('Docker 1'), ('Jenkins 2'), ('K8s 3');
You can use the below command to exit the Postgres terminal.
\q
Step 7: Now delete the Postgres docker container.
docker stop postgres
docker rm postgres
Step 8: Create again a Postgres docker container using the docker volume (created in Step 1).
docker run -d \
--name postgres \
-e POSTGRES_PASSWORD=gfg \
-v postgres_volume:/var/lib/postgresql/data \
postgres:latest
Step 9: Finally go inside the docker container and verify that whether the database and table is present or not. (run the commands below one by one )
docker exec -it postgres psql -U postgres
\c demo_db
SELECT * FROM gfg_articles;
How To Persist Data In A Dockerized Postgres Database Using Volumes ?
Docker and Postgres are two widely used tools in the software development field. Docker simplifies the deployment process by encapsulating applications within a container while Postgres provides a robust and reliable database to store and manage data. In this guide, I will first briefly discuss Docker and Postgres. Then I will guide you through the various steps to persist your Postgres container data using docker volumes.