PostgreSQL database as a docker container
Any technology enthusiast who love to explore new developments in the technology landscape would have come across situations where you would want to have a SQL database with the minimum effort .
PostgreSQL is a good choice in such situations to spin up a lightweight database , which you can even run a docker container.
In this post we are going to set up a docker-compose file for starting up a docker container of PostgreSQL .
Create the docker-compose.yml file in the project root and define the details as given below
version: '3'
services:
airport-db:
image: library/postgres:latest
ports:
- "5432:5432"
container_name: aiport-db-postgres
environment:
- POSTGRES_DB= airport-db
- POSTGRES_PASSWORD=docker
- POSTGRES_USER=docker
volumes:
- ./data:/var/lib/postgresql
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
As you can see we have included an init.sql file which has the database script to create a database objects and to initialise the data.
contents of init.sql is as given below
CREATE TABLE public.airport (
id bigint NOT NULL,
apt_code character varying(255),
apt_name text,
city_name text,
country text
);CREATE SEQUENCE public.apt_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;INSERT INTO public.airport VALUES (1, 'DXB', 'Dubai International Airport', 'Dubai', 'UAE');
INSERT INTO public.airport VALUES (2, 'JFK', 'John F Kennedy International Airport', 'Newyork', 'USA');
INSERT INTO public.airport VALUES (3, 'COK', 'Cochin International Airport', 'Kochi', 'India');SELECT pg_catalog.setval('apt_id_seq', 3, true);
To start the data base use the docker compose up command
docker-compose up
Your PostegreSQL DB with the data base objects defined in the init.sql will be up and running in no time.