首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在测试中使用postgres图像

在测试中使用postgres图像
EN

Stack Overflow用户
提问于 2016-08-04 22:00:47
回答 1查看 166关注 0票数 0

给定以下docker-compose.test.yml文件:

代码语言:javascript
复制
version: '2'
services:
  sut:
    build: .
    command: nosetests
    environment:
      - DJANGO_SETTINGS_MODULE=test.settings
    links:
      - db
  db:
    image: postgres
    expose:
      - 5432

构建sut容器

代码语言:javascript
复制
docker-compose -f docker-compose.test.yml build sut

运行容器:

代码语言:javascript
复制
thomas@linuxclientlobnek01:~/github/djlobnek$ docker-compose -f docker-compose.test.yml run sut /bin/bash 
root@6694ec7148ac:/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?
EN

回答 1

Stack Overflow用户

发布于 2016-08-04 22:31:55

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

代码语言:javascript
复制
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地址。例如:

代码语言:javascript
复制
postgres -h db -U postgres postgres

如果您通过docker exec进入db容器本身,则可以使用localhost作为主机名。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38769519

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档