Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

PostgreSQL

Sample GitHub Action workflow using a Postgres service so we can test our software that relies on a Postgres server.

name: CI

# Add some triggers
on:
  push:
  pull_request:
  workflow_dispatch:
#  schedule:
#    - cron: '42 5 * * *'


jobs:
  test:
    strategy:
      fail-fast: false
      # List some of the tags from https://hub.docker.com/_/postgres
      # You can be very specific or not so specific or just use the latest
      matrix:
        postgres:
          - '16.13-trixie'
          - '17'
          - 'latest'

    # The `services` will launch a separate docker container using the given image
    # That we take from the matrix
    services:
      # We can name our service anything we want. In this case we called it `mypg`.
      # We'll use the same name later.
      mypg:
        image: postgres:${{matrix.postgres}}
        env:
          # We defined some environment variables needed by the the server.
          # They are also used in the client part of this job later in this file.
          POSTGRES_USER: myusername
          POSTGRES_PASSWORD: secret
          POSTGRES_DB: mydb
       # Some magic options needed for the Postgres in the Docker container
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    # This is where we define where and how our code runs
    runs-on: ubuntu-latest
    # It is easier if we also use a Docker container
    container: ubuntu:25.10

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Install curl and ping
        # Install some tools to demonstrate connectivity to the database
        run: |
          apt update
          apt install -y iputils-ping
          apt install -y postgresql-client

      - name: ping postgres
        # The hostname of the postgres server is the name we gave to the service: "mypg"
        run: |
          ping -c 4 mypg

      - name: PostgreSQL CLI psql
        # We set the same "secret" as we set in the service.
        env:
          PGPASSWORD: secret
        # use the username and database name we set in the service above.
        # A few sample SQL statements to show we really have access to Postgres
        run: |
          set -x # show the commands
          echo "SELECT CURRENT_TIME" | psql -h mypg -U myusername mydb
          echo "SELECT version()" | psql -h mypg -U myusername mydb
          echo "CREATE TABLE counter (name text, cnt int)" | psql -h mypg -U myusername mydb
          echo "INSERT INTO counter (name, cnt) VALUES ('foo', 1)" | psql -h mypg -U myusername mydb
          echo "INSERT INTO counter (name, cnt) VALUES ('bar', 42)" | psql -h mypg -U myusername mydb
          echo "SELECT * FROM counter" | psql -h mypg -U myusername mydb