在 github 操作中使用 psql

use*_*360 8 postgresql github psql github-actions

我正在尝试在 github 操作中使用 psql,但看到以下错误:

psql: error: could not connect to server: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
Run Code Online (Sandbox Code Playgroud)

我的 github 操作 yml 文件如下所示(run_all_tests.sh 文件仅调用尝试运行命令 psql 的子进程)。有谁知道为什么会发生这种情况?

name: Python application

on:
  push:
    branches: [master]
  pull_request:
    branches: [master]

jobs:
  build:
    runs-on: ubuntu-latest

    # Service containers to run with `container-job`
    services:
      # Label used to access the service container
      postgres:
        # Docker Hub image
        image: postgres
        # Provide the password for postgres
        env:
          POSTGRES_PASSWORD: postgres
        # Set health checks to wait until postgres has started
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    steps:
      - name: Copy the code
        uses: actions/checkout@v2
      - name: Set up Python 3.8
        uses: actions/setup-python@v2
        with:
          python-version: 3.8
      - name: Install dependencies
        run: |
          python3 setup.py install
      - name: Test with unittest
        run: |
          cd backend/py
          source run_all_tests.sh
        env:
          # The hostname used to communicate with the PostgreSQL service container
          POSTGRES_HOST: postgres
          # The default PostgreSQL port
          POSTGRES_PORT: 5432
Run Code Online (Sandbox Code Playgroud)

小智 8

由于我遇到了同样的问题,因此我尝试了一种对我有用的不同方法。

首先,我在容器中运行该作业:

jobs:
  build:
    container: gradle:jdk11
Run Code Online (Sandbox Code Playgroud)

这不会使该psql命令可用,因此您需要添加一个运行步骤来安装它。根据您选择的 Docker 镜像,具体安装方法可能会有所不同:

jobs:
  build:
    container: gradle:jdk11
    ...
    steps:
      - run: |
          apt-get update
          apt-get install --yes --no-install-recommends postgresql-client
Run Code Online (Sandbox Code Playgroud)

请注意,您可能有上面或下面不同的步骤。

现在是时候执行您需要的所有这些 SQL 了。这里最重要的是:数据库主机名是postgres服务容器的id。


jobs:
  build:
    container: gradle:jdk11
    ...
    steps:
      - run: |
          apt-get update
          apt-get install --yes --no-install-recommends postgresql-client
      - run: |
          psql -h postgres -U postgres -c 'CREATE DATABASE ...'
          psql -h postgres -U postgres -c 'CREATE ROLE ...'
Run Code Online (Sandbox Code Playgroud)