Sitemap

Initialise postgres container with data

1 min readOct 4, 2024

Get the data initialised with the container

Create a docker-compose.yml

services:
postgress-postgresql:
image: postgres:bullseye
container_name: postgres
volumes:
- postgresql_data:/var/lib/postgresql/data/
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
environment:
- POSTGRES_USER=postgress
- POSTGRES_PASSWORD=MyStrongPassword123
ports:
- 5432:5432
networks:
- postgres
networks:
postgres:
volumes:
postgresql_data:

Create a init.sql with the script

CREATE USER vbv WITH PASSWORD 'vbv';
CREATE DATABASE vbvdb;
GRANT ALL PRIVILEGES ON DATABASE vbvdb TO vbv;

\connect vbvdb;

CREATE TABLE employees (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
position VARCHAR(50),
salary DECIMAL(10, 2)
);

INSERT INTO employees (name, position, salary) VALUES
('Bhuvi', 'Manager', 675000.00),
('Vibhu', 'Developer', 555000.00),
('Rudra', 'Analyst', 460000.00);

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO vbv;

RUN with docker compose up -d

Connect to the container psql client - docker exec -it postgres bash. Check the data exists.

➜  ~ docker exec -it postgres bash
root@96a599122941:/# psql -U vbv -d vbvdb
psql (17.0 (Debian 17.0-1.pgdg110+1))
Type "help" for help.

vbvdb=> SELECT * FROM employees;
id | name | position | salary
----+-------+-----------+----------
1 | Bhuvi | Manager | 675000.00
2 | Vibhu | Developer | 555000.00
3 | Rudra | Analyst | 460000.00
(3 rows)

vbvdb=>

You can also validate docker logs -f postgres contains the following.

2024-10-04 08:04:03.810 UTC [48] LOG:  database system is ready to accept connections
done
server started
CREATE DATABASE


/usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/init.sql
CREATE ROLE
CREATE DATABASE
GRANT
You are now connected to database "vbvdb" as user "postgress".
CREATE TABLE
INSERT 0 3
GRANT

Activity log : https://gist.github.com/jinnabaalu/89bd8eeba3b8845cf337b85a807748f1

--

--

Jinna Baalu
Jinna Baalu

Written by Jinna Baalu

Devops Solution Architect | Managing Consensus based Distributed Clusters | Centralised Logging 4M/15min | ELK | Prometheus | Kafka | Cassandra | Mongo

No responses yet