Django无法连接到gitlab ci中的postgres数据库

Django无法连接到gitlab ci中的postgres数据库,django,docker,continuous-integration,Django,Docker,Continuous Integration,我有以下内容。gitlab-ci.yml: image: python:3.6 stages: - lint - test services: - postgres:10.1-alpine cache: paths: - /root/.local/share/virtualenvs/ before_script: - python -V - pip install pipenv - pipenv install --dev lint: stage:

我有以下内容。gitlab-ci.yml:

image: python:3.6

stages:
  - lint
  - test

services:
  - postgres:10.1-alpine

cache:
  paths:
  - /root/.local/share/virtualenvs/

before_script:
  - python -V
  - pip install pipenv
  - pipenv install --dev

lint:
  stage: lint
  script:
  - pipenv run pylint --output-format=text --load-plugins pylint_django project/ | tee pylint.txt
  - score=$(sed -n 's/^Your code has been rated at \([-0-9.]*\)\/.*/\1/p' pylint.txt)
  - echo "Pylint score was $score"
  - pipenv run anybadge --value=$score --file=pylint.svg pylint
  artifacts:
    paths:
      - pylint.svg

test:
  stage: test
  script:
  - pipenv run python manage.py test
我是这样连接到数据库的:

# settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER': 'postgres',
        'PASSWORD': '',
        'HOST': 'db', # set in docker-compose.yml
        'PORT': 5432 # default postgres port
    }
}
现在,我只在
users/tests.py
中进行了以下测试:

from .models import CustomUser
from django.test import TestCase

class LogInTest(TestCase):
    def setUp(self):
        self.credentials = {
            'username': 'testuser',
            'password': 'secret'}
        CustomUser.objects.create_user(**self.credentials)
    def testLogin(self):
        # send login data
        response = self.client.post('/users/login/', self.credentials, follow=True)
        # should be logged in now
        self.assertTrue(response.context['user'].is_authenticated)
失败,出现以下错误:

psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known 
在开发中,我使用以下docker-compose.yml文件:

version: '3.3'

services:
  db:
    image: postgres:10.1-alpine
    volumes:
      - postgres_data:/var/lib/postgresql/data/

  web:
    build: .
    command: python /code/manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - 8000:8000
    environment:
      - SECRET_KEY=changemeinprod
    depends_on:
      - db

volumes:
  postgres_data:
使用此Dockerfile:

FROM python:3.6

# Set environment varibles
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# Set work directory
WORKDIR /code

# Install dependencies
RUN pip install --upgrade pip
RUN pip install pipenv
COPY ./Pipfile /code/Pipfile
RUN pipenv install --deploy --system --skip-lock --dev

# Copy project
COPY . /code/

我不明白为什么应用程序cab没有连接到CI中的数据库,而是在开发环境中用docker在你的docker compose.yml中将服务名称设置为
db
,django
settings.py
使用
db
,但是在gitlab中将使用图像名称作为服务名称,
postgres
以防万一

您有两个选择:

1-在
settings.py
中使用环境变量,例如

2-在gitlab-ci.yml中设置一个
别名,如:

服务:
-姓名:博士后:10.1-10
别名:db
链接: