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

时间:2018-11-02 20:33:23

标签: 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: 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/

我不明白为什么应用程序无法连接到CI中的数据库,而在开发环境中与docker很好地连接

1 个答案:

答案 0 :(得分:1)

在您的docker-compose.yml中,将服务名称设置为db,将Django settings.py设置为使用db,但在gitlab中,它将图像名称用作服务,以防postgres

您有两个选择:

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

2-在gitlab-ci.yml中设置alias,例如:

services: - name: postgres:10.1-alpine alias: db 链接:gitlab docs