0

在 docker 中使用 gitlab-ci 测试失败,因为Postgres服务无法访问。

在我的开发环境中,我成功地运行了测试:$docker-compose -f local.yaml run web py.test

但在 gitlab 中,- docker run --env-file=.env_dev $CONTAINER_TEST_IMAGE py.test -p no:sugargitlab-ci.yaml 文件中的命令失败并显示:

9bfe10de3baf: Pull complete
a137c036644b: Pull complete
8ad45b31cc3c: Pull complete
Digest: sha256:0897b57e12bd2bd63bdf3d9473fb73a150dc4f20cc3440822136ca511417762b
Status: Downloaded newer image for registry.gitlab.com/myaccount/myapp:gitlab_ci
$ docker run --env-file=.env $CONTAINER_TEST_IMAGE py.test -p no:sugar
Postgres is unavailable - sleeping
Postgres is unavailable - sleeping
Postgres is unavailable - sleeping
Postgres is unavailable - sleeping
Postgres is unavailable - sleeping

基本上,它看不到 Postgres 服务。文本Postgres is unavailable - sleeping来自一个 entrypoint.sh 文件Dockerfile

以下是一些相关文件:

gitlab-ci.yml

image: docker:latest

services:
  - docker:dind

stages:
  - build
  - test

variables:
  CONTAINER_TEST_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME


before_script:
  - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY

build:
  stage: build
  script:
    - docker build --pull -t $CONTAINER_TEST_IMAGE --file compose/local/django/Dockerfile .
    - docker push $CONTAINER_TEST_IMAGE

pytest:
  stage: test
  script:
    - docker pull $CONTAINER_TEST_IMAGE
    - docker run --env-file=.env_dev $CONTAINER_TEST_IMAGE py.test -p no:sugar
  when: on_success

Dockerfile:

# ... other configs here
ENTRYPOINT ["compose/local/django/entrypoint.sh"]

入口点.sh:

# ..... other configs here

export DATABASE_URL=postgres://$POSTGRES_USER:$POSTGRES_PASSWORD@postgres:5432/$POSTGRES_USER

function postgres_ready(){
python << END
import sys
import psycopg2
try:
    conn = psycopg2.connect(dbname="$POSTGRES_USER", user="$POSTGRES_USER", password="$POSTGRES_PASSWORD", host="postgres")
except psycopg2.OperationalError:
    sys.exit(-1)
sys.exit(0)
END
}

until postgres_ready; do
  >&2 echo "Postgres is unavailable - sleeping"
  sleep 1
done

>&2 echo "Postgres is up - continuing..."
exec $cmd

上面的设置和配置灵感来自django-cookie-cutter

4

0 回答 0