Postgres is a schema based database application that is used to store data for your application. In this post you will learn to install Postgres using docker compose. Postgres is a Relational database used to store valuable information. Docker is a tool used to containerize your application such that it becomes operating system agnostic. Now a days the adoption of docker is all time high and it is good to learn docker technologies to keep you updated.

Prerequisite

  • Docker must be installed
  • Docker Composer must be installed

Create a YAML file

touch postgres-docker-compose.yml

Put the below contents in the mysql-docker-compose.yml file


version: '3.8'
services:
  postgres:
    image: postgres:14.1-alpine
    restart: always
    environment:
      - POSTGRES_USER=postgres        # Username for your postgres datbase
      - POSTGRES_PASSWORD=postgres    # Password for your postgres user
    ports:
      - '5432:5432'
    volumes: 
      - db:/var/lib/postgresql/data
volumes:
  db:
    driver: local

Above Docker compose file will help you to create a Postgres Database instance. The important points about that instance will be

  • A user with the name postgres will be created. You will need this user for your database connection.
  • The password for that postgres user will be postgres

you can change these values in the environment section of YAML file

Starting the services

you can start the service in Foreground mode using

docker-compose -f postgres-docker-compose.yml up

if you want to start the service in background mode then you can use

docker-compose -f postgres-docker-compose.yml up -d

You can connect the MySQL server running

  • UserName = postgres
  • Password = postgres
  • Host = localhost or 127.0.0.1
  • Port = 5432

Installing the psql client

once Postgres is installed in using docker compose then your need to connect it from outside. For this you need to have the psql client installed in your machine

If your machine is Ubuntu then you can use below command to install the required libraries

sudo apt-get install -y postgresql-client

Connect Postgres using psql client

once psql client is available then you can use the below command to connect to postgres

psql -h 127.0.0.1 -U postgres

This will ask you to enter your password

you need to enter the password as postgres and then it will take you to the postgres terminal

You can get the list of all Docker Compose file in my GitHub Repository

Happy Coding

Leave a Reply

Your email address will not be published. Required fields are marked *