Docker: Your First PostgreSQL Connection in 10 mins

tanut aran
CODEMONDAY
Published in
2 min readJun 18, 2020

--

First of all, getting the Docker.

If you’re confuse with docker and docker compose , it is the same things.

docker reads from command line input.

docker compose reads from file.

Both Docker and Docker Compose work on server and desktop. We’re developing on the desktop. So go to the download page then download Docker for Desktop.

Docker

This is one command to run

$ docker run -p 5436:5432 \
-e POSTGRES_DB=my_database \
-e POSTGRES_USER=admin \
-e POSTGRES_PASSWORD=123456 \
-v ./postgres-initdb.sh:/docker-entrypoint-initdb.d/init.sh \
postgres

Docker Compose

The only difference is putting in long command to docker-compose.yml file.

So you don’t have to type in long command every time.

The Docker Compose equivalent looks like:

services:
my-postgres:
ports:
- '5436:5432'
restart: always
image: postgres
environment:
POSTGRES_DB: my_database
POSTGRES_USER: admin
POSTGRES_PASSWORD: 123456
volumes:
- ./postgres-initdb.sh:/docker-entrypoint-initdb.d/init.sh

Port expose

The most important line here is:

ports:
- '5436:5432'

This means you can connect to this ‘VM’* through port 5436 and this PostgreSQL is running on the VM on port 5432

*Not actually VM (Virtual Machine) but for simplicity pretends it is for a while.

Note that the syntax have two style. First is Hash key style:

environment:
POSTGRES_USER: admin

and the second is listing style

environment:
- POSTGRES_USER=admin

Both is working

Running the compose file

The default way to run is:

$ docker compose up

You might need to specific path if the docker-compose.yml file is not in the same directory.

$ docker compose -f ./path/to/docker-compose.yml up

Connection

Download the PostgreSQL client name psql and use it to test the connection

$ psql -h localhost -p 5436 -U admin -d my_database

The confusing at the end my_database must be specified otherwise error. This is because the ‘user’ admin and its ‘role’ only working on the my_database .

Common Error

psql: FATAL:  role "admin" does not exist

Stop the container and delete the old one. It’s about clearing the cache and start the brand new one.

Here is it. So development can start from now.

Cheers.

Notes: docker compose VS docker-compose

As-of 2022 there will be no more docker-compose but it combine into Docker main CLI as docker compose (space) instead

Web Application | IoT

www.codemonday.com

--

--