Django app in Docker container unable to find post

2019-05-23 04:22发布

I have a Django application on gitlab and I am trying to add CI/CD using gitlab-ci. I started a server on EC2 and installed gitlab-runner on it.

I added .gitlab-ci.yml file to my project and pushed the latest changes. I can see the pipeline running and dependencies being installed. But When the script tries to run tests, I get an error like this:

django.db.utils.OperationalError: 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?

Below is my .gitlab-ci.yaml script:

image: python:3-jessie

services:
  - postgres:latest

before_script:
  - python -V
  - apt-get -y update
  - apt-get install -y python-dev python-pip
  - pip install --upgrade pip

stages:
  - build

build:
  type: build
  variables:
    DATABASE_URL: postgres://postgres:@postgres:5432/opensys_erp
  script:
  - pip install -r requirements.txt
  - python manage.py test
  only:
  - branches

Why is my application unable to connect to postgres server?

2条回答
冷血范
2楼-- · 2019-05-23 04:45

As your container try to connect postgres on their own localhost that's why you getting connection refused. 127.0.0.1 this localhost is the localhost of Django application container. To connect with postgress using localhost you need to link your docker container.

Docker also has a linking system that allows you to link multiple containers together and send connection information from one to another. When containers are linked, information about a source container can be sent to a recipient container.

How services are linked to the job

To summarize, if you add mysql as service to your application, the image will then be used to create a container that is linked to the job container.

The service container for MySQL will be accessible under the hostname mysql. So, in order to access your database service you have to connect to the host named mysql instead of a socket or localhost.

A day before I post a detailed answer for the same sort of question you check this as well.

https://stackoverflow.com/a/49342027/3288890

You can check some links

https://docs.docker.com/network/links/

https://docs.gitlab.com/ce/ci/docker/using_docker_images.html

https://docs.gitlab.com/ce/ci/docker/using_docker_images.html#accessing-the-services

查看更多
仙女界的扛把子
3楼-- · 2019-05-23 05:00

If I interpret the docs correct, you should remove the : after the postgres user:

postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]

So your string would be:

postgres://postgres@postgres:5432/opensys_erp

查看更多
登录 后发表回答