首页 > 解决方案 > 带有 Postgres 错误的 GitLab CI:连接 ECONNREFUSED 127.0.0.1:5432

问题描述

我有一个Gitlab CI pipeline哪些测试、构建和部署代码。该代码基本上是一个 nodejs api,并且使用Sequelize ORM. 最近,我尝试了使用Postgres Database.

这是gitlab-ci.yml文件:

image: trion/ng-cli-karma

variables:
  POSTGRES_DB: test
  POSTGRES_USER: postgres
  POSTGRES_PASSWORD: password
  NODE_ENV: test

cache:
  paths:
  - wiki-quotes-client/node_modules/
  - wiki-quotes-server/node_modules/

stages:
    - test
    - build
    - deploy

test_server:
  services:
   - postgres:latest
  script:
   - cd wiki-quotes-server
   - npm install
   - npm install -g sequelize-cli
   - sequelize db:migrate
   - sequelize db:seed:all
   - npm run test

test_client:
    script:
        -  cd wiki-quotes-client
        -  npm install
        -  ng test --watch=false

build_angular:
  only:
    - master
  stage: build
  script:
    - npm install
    - cd wiki-quotes-client
    - ng build --prod
  artifacts:
    paths:
      - wiki-quotes-client/dist/wiki-quotes-client/.

deploy:
  only:
    - master
  stage: deploy
  dependencies:
    - build_angular
  script:
    - ls -all
    - apt-get update -qq
    - apt-get install -qq git
    - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
    - eval $(ssh-agent -s)
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - echo "$SSH_KEY" | tr -d '\r' | ssh-add - > /dev/null
    - ls ~/.ssh/
    - '[[ -f /.dockerenv ]] && echo -e "Host *\n\t StrictHostKeyChecking no \n\n" > ~/.ssh/config'
    - ssh-keyscan 159.65.156.240 >> ~/.ssh/known_hosts
    - chmod 644 ~/.ssh/known_hosts
    - ssh goutambseervi@159.65.156.240 'cd ~/wikiquotesapp; git checkout master; git pull;  cd wiki-quotes-server; npm install; npm start:prod'

现在它向我显示了这个错误:

错误:连接 ECONNREFUSED 127.0.0.1:5432

另外,我还有一个问题是......

当我使用数据库部署 api 时,理想的路径是Sequelize什么?

我想确保我的迁移上线,同时每次部署时都应该为我的数据库播种,我不希望数据库有冗余数据。

标签: node.jspostgresqlgitlabsequelize.jsgitlab-ci

解决方案


在 Gitlab CI 中使用服务的工作方式与运行不同的 docker 容器(docker-compose 中的命名服务)基本相同,这些容器可用于运行特定作业的容器。

因此,根据您的错误消息,我假设您的代码尝试访问 postgres 数据库localhost,当您在开发人员机器上同时运行这两个数据库时,该数据库可以工作。在 Gitlab CI 中,这两个容器“都有自己的localhost”,并且必须使用 dns 名称postgres来连接到另一个容器。因此,当您使用名为 的图像postgres时,Gitlab 也会这样命名服务。

请尝试在节点进程中使用主机名postgres而不是localhost数据库连接,并且访问应该可以工作。根据您定义的其他变量,这可能已经通过添加一个以上variablePOSTGRES_HOST: postgres或类似的 - 我不熟悉 sequelize 配置)

有关 Gitlab CI 中服务的详细信息,请查看文档,这些文档postgres甚至为您访问服务的特定用例提供了示例,并对此特定问题进行了一些澄清


推荐阅读