DEV Community

Cover image for Install PostgreSQL in a Docker Container
Aung Thu Oo
Aung Thu Oo

Posted on

Install PostgreSQL in a Docker Container

Install PostgreSQL in a Docker Container: A Beginner's Guide

1. Prerequisites

  • Docker installed on your machine
  • Node.js installed on your machine

2. Preparation

Create any folder you want, and then open it with your terminal.

mkdir <YOUR_FOLDER>
cd <YOUR_FOLDER>
code .
Enter fullscreen mode Exit fullscreen mode

3. Initialize a git repository.

git init
touch .gitignore
Enter fullscreen mode Exit fullscreen mode

Populate the .gitignore file with the following content:

*node_modules
Enter fullscreen mode Exit fullscreen mode

Create a file called compose.yaml in the project's root.

touch compose.yaml
Enter fullscreen mode Exit fullscreen mode

4. Database

I will use Postgres but not install it on my machine. Instead, I will use Docker to run it in a container. This way, I can easily start and stop the database without installing it on my machine.

Open the file compose.yaml and add the following content:

version: '3.9'

services:
  db:
    container_name: pgdb
    image: postgres:12
    restart: always
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: postgres
    ports:
      - 5432:5432
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata: {}
Enter fullscreen mode Exit fullscreen mode

then type in your terminal

docker compose up -d
Enter fullscreen mode Exit fullscreen mode

This will pull the Postgres image from Docker Hub and start the container.
The -d flag means that the container will run in detached mode so we can continue to use the terminal.

5.Testing

To check if the container is running:

docker ps -a
Enter fullscreen mode Exit fullscreen mode

Step into the db container

docker exec -it pgdb psql -U postgres
Enter fullscreen mode Exit fullscreen mode

Now that you are in the Postgres container, you can type:

\l
Enter fullscreen mode Exit fullscreen mode

Screenshot from 2024-09-20 11-37-23

\dt
Enter fullscreen mode Exit fullscreen mode

And you should see no relations.

You can now exit the container with the exit command.

exit  
Enter fullscreen mode Exit fullscreen mode

Top comments (0)