2022-10-24 21:41:05 +11:00

3.1 KiB

Introduction to PostgreSQL

This is part 1 of my series on learning PostgreSQL.
The primary focus is getting PostgreSQL up and running and
taking a first look at the database.

PostgreSQL Docker Image

Run a simple PostgreSQL database (docker)

 docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres

Run a simple PostgreSQL database (compose)

docker compose up

We can access our database from the adminer webpage on http://localhost8080

When running containers, its always important to pull the image by tag
to ensure you always get the same container image, else it will pull latest.
We will do that in the next step.

Persisting Data

To persist data to Postgres, we simply mount a docker volume.
This is the way to persist container data.
Postgres stores its data by default under /var/lib/postgresql/data Also take note we are running a specific version of Postges now:

docker run -it --rm --name postgres `
  -e POSTGRES_PASSWORD=admin123 `
  -v ${PWD}/pgdata:/var/lib/postgresql/data `
  postgres:15.0

We can enter the container to connect to SQL:

# enter the container
docker exec -it postgres bash

# login to postgres
psql -h localhost -U postgres

#create a table
CREATE TABLE customers (firstname text,lastname text, customer_id serial);

#add record
INSERT INTO customers (firstname, lastname) VALUES ( 'Bob', 'Smith');

#show table
\dt

# get records
SELECT * FROM customers;

# quit 
\q

Now we can see our data persisted by killing and removing the container:

docker rm -f postgres

Run it again with the above docker run command and list our record with the above commands we've learnt

Networking

Postgres by default uses port 5432.
Since we are running in Docker, we can bind a differnt port if we wish with Docker's -p flag.
For example, we can expose port 5000 outside the container :

docker run -it --rm --name postgres `
  -e POSTGRES_PASSWORD=admin123 `
  -v ${PWD}/pgdata:/var/lib/postgresql/data `
  -p 5000:5432 `
  postgres:15.0

Note that this does not change the port which Postgres runs on.
To change that, we need to explore the configuration.

Configuration

PostgreSQL can be configured using environment variables as well as a config file.

Postgres has a ton of configuration options.
In the next chapter, we will explore the configuration of Postgres.

Docker Compose

Let's update our compose file to reflect our latest changes.

We need to update the docker image, the port we want to expose outside of the container as well as a volume mount for persistence.

version: '3.1'
services:
  db:
    image: postgres:15.0
    restart: always
    environment:
      POSTGRES_PASSWORD: admin123
    ports:
    - 5000:5432
    volumes:
    - ./pgdata:/var/lib/postgresql/data
  adminer:
    image: adminer
    restart: always
    ports:
      - 8080:8080