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

Aung Thu Oo
2 min readSep 22, 2024

--

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 .

3. Initialize a git repository.

git init
touch .gitignore

Populate the .gitignore file with the following content:

*node_modules

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

touch compose.yaml

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: {}

then type in your terminal

docker compose up -d

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

Step into the db container

docker exec -it pgdb psql -U postgres

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

\l
\dt

And you should see no relations.

You can now exit the container with the exit command.

exit

#daily_dev_note

--

--

Aung Thu Oo

Senior Developer (Nex.js, React.js, Node.js, Laravel, Flutter)