To Run PostgreSQL in Docker I use an official image ‘postgres’ from https://hub.docker.com/_/postgres. You can start it as it’s described in the documentation, but I prefer to use docker-compose. For me it’s more flexible and allows to avoid of errors when start form command line.

For example, you can use this code of ‘docker-compose.yml’.

# A Docker Compose must always start with the version tag.
# We use '3' because it's the last version.
version: '3'

services:
  # The name of our service is "database"
  database:
    # Official Postgres image from DockerHub (we use the last version)
    image: 'postgres:latest'

    ports:
      - 5432:5432

    environment:
      POSTGRES_DB: "alex"
      POSTGRES_USER: "alex"
      POSTGRES_PASSWORD: "alex"
      PGDATA: "/var/lib/postgresql/data/pgdata"

    # The `volumes` tag allows us to share a folder with our container
    # Its syntax is as follows: [folder path on our machine]:[folder path to retrieve in the container]
    volumes:
      - ./db-data/:/var/lib/postgresql/data/
    healthcheck:
        test: ["CMD-SHELL", "pg_isready -U alex -d alex"]
        interval: 10s
        timeout: 5s
        retries: 5
        start_period: 10s
    restart: unless-stopped

Save this file in a directory and then open it in a console and type

docker-compose -up

It will create a Container and executes it. Now you can connect to your database form DBeaver or your application

You can also enter the postgresql console. For that execute in console

docker ps

Next execute

docker exec -it bc5aba4d82f8  bash

to enter the console of your docker. There you can execute the command:

psql -U alex

and manage your DB form command line.

This example is without environment variables. It’s not secured and can be used only for demo or tests.