无法基于postgres连接到容器

时间:2017-11-13 14:21:06

标签: python postgresql docker docker-compose

我是docker容器的新手。我正在尝试自动对Circle CI上的Flask应用程序进行单元测试。但它无法连接到postgres容器。它适用于我的本地计算机(macOS Sierra)。如果您需要更多信息来解决此问题,请与我们联系。谢谢!!

搬运工-compose.yml

version: '3'
services:
  web:
    container_name: web
    build: ./web
    ports:
      - "5000:5000"
    depends_on:
      - postgres
    volumes:
      - ./web/.:/app
    tty: true

  postgres:
    container_name: postgres
    build: ./db
    ports:
      - "5432:5432"

config.yml

version: 2
jobs:
  build:
    machine: true

    working_directory: ~/repo

    steps:
      - checkout

      - run:
          name: Install Docker Compose
          command: |
            sudo curl -L https://github.com/docker/compose/releases/download/1.16.1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
            sudo chmod +x /usr/local/bin/docker-compose

      - run:
          name: Start container and veryfy it's working
          command: |
            set -x
            cd ~/repo/docker
            docker-compose up --build -d
      - run:
          name: Run test
          command: |
            cd ~/repo/docker
            docker-compose run web python tests/test_therapies.py

Circle Ci构建日志

    connection = pool._invoke_creator(self)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/strategies.py", line 105, in connect
    return dialect.connect(*cargs, **cparams)
  File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 393, in connect
    return self.dbapi.connect(*cargs, **cparams)
  File "/usr/local/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused
    Is the server running on host "postgres" (172.18.0.2) and accepting
    TCP/IP connections on port 5432?


----------------------------------------------------------------------
Ran 1 test in 0.025s

FAILED (errors=1)
    Exited with code 1

1 个答案:

答案 0 :(得分:1)

我认为问题在于,当您的网络应用启动时,postgres服务并未完全启动。根据你在添加睡眠计时器后对它的评论,这似乎是问题所在。

您可以运行一个名为dadarek/wait-for-dependencies的容器作为等待服务启动的机制(在您的情况下,postgres)。

以下是如何实施它:

1)。将新服务添加到docker-compose.yml

  waitfordb:
    image: dadarek/wait-for-dependencies
    depends_on:
      - postgres 
    command: postgres:5432

您的docker-compose.yml现在应该看起来像这样:

version: '3'
services:
  waitfordb:
    image: dadarek/wait-for-dependencies
    depends_on:
      - postgres 
    command: postgres:5432

  web:
    container_name: web
    build: ./web
    ports:
      - "5000:5000"
    depends_on:
      - waitfordb
      - postgres
    volumes:
      - ./web/.:/app
    tty: true

  postgres:
    container_name: postgres
    build: ./db
    ports:
      - "5432:5432"

2)。启动撰写

docker-compose run --rm waitfordb
docker-compose up -d web postgres

结果是您的web服务现在应该等待端口5432在您的postgres容器中启动,然后再尝试启动。