【问题标题】:Django app in Docker container unable to find postgresDocker 容器中的 Django 应用程序无法找到 postgres
【发布时间】:2018-03-20 05:35:28
【问题描述】:

我在 gitlab 上有一个 Django 应用程序,我正在尝试使用 gitlab-ci 添加 CI/CD。我在 EC2 上启动了一个服务器,并在上面安装了 gitlab-runner。

我在我的项目中添加了.gitlab-ci.yml 文件并推送了最新的更改。我可以看到正在运行的管道和正在安装的依赖项。但是当脚本尝试运行测试时,我收到如下错误:

django.db.utils.OperationalError:无法连接到服务器:连接被拒绝

服务器是否在主机“localhost”(::1) 上运行并接受 端口 5432 上的 TCP/IP 连接?

无法连接到服务器:连接被拒绝

服务器是否在主机“localhost”(127.0.0.1) 上运行并接受 端口 5432 上的 TCP/IP 连接?

下面是我的.gitlab-ci.yaml 脚本:

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

为什么我的应用程序无法连接到 postgres 服务器?

【问题讨论】:

    标签: postgresql docker gitlab-ci


    【解决方案1】:

    当您的容器尝试在自己的本地主机上连接 postgres 时,这就是您连接被拒绝的原因。 127.0.0.1 这个 localhost 是 Django application 容器的 localhost。要使用 localhost 与 postgress 连接,您需要 link 您的 docker 容器。

    Docker 还有一个链接系统,允许您将多个容器链接在一起并将连接信息从一个容器发送到另一个容器。链接容器后,可以将有关源容器的信息发送到接收容器。

    服务如何与工作相关联

    总而言之,如果您将 mysql 作为服务添加到您的应用程序,则该映像将用于创建一个容器,该容器链接到作业容器。

    可以在主机名下访问 MySQL 的服务容器 mysql。因此,为了访问您的数据库服务,您必须 连接到名为 mysql 的主机,而不是套接字或 localhost。

    在我发布同类型问题的详细答案前一天,你也检查了这个。

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

    你可以查看一些链接

    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

    【讨论】:

    • 谢谢它的工作。但有一个小问题。我的应用程序是一个 django 项目,在本地我使用主机作为localhost。有什么办法可以将我的设置文件中的本地主机映射到'.gitlab-ci.yml`中的postgres
    • 是的,如果您链​​接您的 contianer,您将使用 contianer 名称作为主机。例如,您将 php 与 db 链接,并且 mysql contianer 名称是 db,那么您的 localhost 将不再需要您可以使用 db,它将指向您的 mysql 的 contianer。如果容器中的 exec 将在 php 容器 etc/hosts 中看到 db 的条目,其中 db 将使用其 docker netwrok ip 指向 mysql contianer。
    【解决方案2】:

    如果我对 docs 的解释正确,您应该删除 postgres 用户之后的 :

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

    所以你的字符串是:

    postgres://postgres@postgres:5432/opensys_erp

    【讨论】:

    • 您的应用程序是否正确读取了DATABASE_URL
    猜你喜欢
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 2019-11-15
    • 2020-12-30
    • 2019-08-11
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多