2016-08-04 19 views
0

考虑下面的码头工人,compose.test.yml文件:在测试使用Postgres的图像

version: '2' 
services: 
    sut: 
    build: . 
    command: nosetests 
    environment: 
     - DJANGO_SETTINGS_MODULE=test.settings 
    links: 
     - db 
    db: 
    image: postgres 
    expose: 
     - 5432 

构建SUT容器

docker-compose -f docker-compose.test.yml build sut 

运行容器:

[email protected]:~/github/djlobnek$ docker-compose -f docker-compose.test.yml run sut /bin/bash 
[email protected]:/djlobnek# psql -h localhost -U postgres 
psql: 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? 

回答

1

在数据库准备好接受连接之前,您的应用程序可能尝试连接到数据库。如果是这种情况,那么在sut容器中实现某种等待数据库循环即可解决问题。我已经在过去使用的是这样的:

while ! psql -h db -U postgres postgres -c 'select 1'; do 
    echo "waiting for database" 
    sleep 1 
done 

这是不必要的,如果你的应用程序知道如何重试不成功的数据库连接。

您尝试在此之前,它验证的Postgres容器实际上是功能(例如,通过与docker exec进入sut容器,并尝试使用psql手动连接)一个好主意。

更新

试图从sut容器内连接到localhost是不行的(Postgres的不说,容器内运行)。您需要使用主机名称db,否则您需要使用db容器的IP地址。 E.g:

postgres -h db -U postgres postgres 

您可以使用localhost作为主机名,如果你docker execdb容器本身。

+0

我使用{docker-compose -f docker-compose.test.yml run sut/bin/bash}直接连接到sut层。我已经在dockerfile中安装了postgresql-client。运行{psql -h localhost -U postgres}不成功 – tschm

+0

确实,了解了localhost问题。我现在确实可以连接到容器,并且可以使用psql启动postgres命令行,例如, thomas @ linuxclientlobnek01:〜/ github/djlobnek $ docker-compose -p test -f docker-compose.test.yml运行sut/bin/bash root @ 245ad3d10a9b:/ djlobnek#psql -h db -U postgres该工作,然而... – tschm

+0

当然,重点是自动化这一点,在这里我仍然面临问题。所以注意我的命令有多类似:docker-compose -p test -f docker-compose.test.yml运行sut。在这里,测试失败,上述被拒绝的连接相同 – tschm