给定以下docker-compose.test.yml文件:
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运行容器:
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?发布于 2016-08-04 22:31:55
在数据库准备好接受连接之前,您的应用程序可能正在尝试连接到数据库。如果是这样,那么在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地址。例如:
postgres -h db -U postgres postgres如果您通过docker exec进入db容器本身,则可以使用localhost作为主机名。
https://stackoverflow.com/questions/38769519
复制相似问题