在 Gitlab-CI 上启动 postgres 服务

use*_*003 5 postgresql ruby-on-rails gitlab gitlab-ci

我有一个使用 Postgres 的 Rails5 应用程序。当我推送新提交时,我正在尝试使用 Gitlab CI 来运行我的规范测试。

我尝试根据配置 .gitlab-ci.yml 文件和使用 postgres 服务的文档设置我的文件

我没有改变我的跑步者,所以它在运行 Gitlab 使用的任何默认设置。

.gitlab-ci.yml

services:
  - postgres:9.6

variables:
  POSTGRES_DB: galapagos_test
  POSTGRES_USER: runner
  POSTGRES_PASSWORD: ""

before_script:
  # System
  - apt-get update -qq

  # Ruby
  - ruby -v
  - which ruby

  # Gems
  - 'echo ''gem: --no-ri --no-rdoc'' > ~/.gemrc'
  - gem install bundler
  - bundle install --without production --jobs $(nproc) "${FLAGS[@]}"

  # App
  - RAILS_ENV=test bundle exec rake db:create
  - RAILS_ENV=test bundle exec rake db:migrate

rspec:
  script:
    - bundle exec rspec
Run Code Online (Sandbox Code Playgroud)

数据库.yml

我的 Rails 应用程序database.yml配置为使用上面指定的相同的 postgres 数据库、用户名和密码

development: &default
  adapter: postgresql
  database: galapagos_development
  encoding: utf8
  host: localhost
  min_messages: warning
  pool: 2
  timeout: 5000

test:
  <<: *default
  database: galapagos_test
  user: runner
  password: ""
Run Code Online (Sandbox Code Playgroud)

错误

当构建运行时,它会不断地使rake任务失败

$ RAILS_ENV=test bundle exec rake db:create
could not connect to server: Connection refused
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?
could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?
Couldn't create database for {"adapter"=>"postgresql", "database"=>"galapagos_test", "encoding"=>"utf8", "host"=>"localhost", "min_messages"=>"warning", "pool"=>2, "timeout"=>5000, "user"=>"runner", "password"=>""}
rake aborted!
PG::ConnectionBad: could not connect to server: Connection refused
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?
could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?
/usr/local/bundle/gems/pg-0.20.0/lib/pg.rb:56:in `initialize'
/usr/local/bundle/gems/pg-0.20.0/lib/pg.rb:56:in `new'
/usr/local/bundle/gems/pg-0.20.0/lib/pg.rb:56:in `connect'
Run Code Online (Sandbox Code Playgroud)

显然 postgres 服务已安装(构建日志表明9.6已安装)但 psql 服务器未启动。

如何启动 postgres 服务?

我尝试了我见过的 2 个“常见”解决方案,但它们也都会产生错误。

$ /etc/init.d/postgresql restart
/bin/bash: line 69: /etc/init.d/postgresql: No such file or directory
ERROR: Job failed: exit code 1


$ service postgresql start
postgresql: unrecognized service
ERROR: Job failed: exit code 1
Run Code Online (Sandbox Code Playgroud)

Sas*_*ken 5

更改host: localhost为host: postgres您的database.yml.

服务是另一个无法在本地访问的容器。因此,您必须通过主机名(默认情况下是服务的名称)来访问它。如果需要文档,您可以为服务设置可选别名