在testing中使用postgres图像
鉴于以下docker-compose.test.yml文件:
version: '2' services: sut: build: . command: nosetests environment: - DJANGO_SETTINGS_MODULE=test.settings links: - db db: image: postgres expose: - 5432
build立一个容器
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?
在数据库准备好接受连接之前,您的应用程序可能正试图连接到数据库。 如果是这种情况,那么在sut
容器中实现某种等待数据库循环可以解决问题。 我过去曾经用过这样的东西:
while ! psql -h db -U postgres postgres -c 'select 1'; do echo "waiting for database" sleep 1 done
如果您的应用程序知道如何重试不成功的数据库连接,这是不必要的。
在你尝试这个之前,validationpostgres容器是否真正运行是一个好主意(例如,通过sut
docker exec
进入sut
容器并尝试使用psql
手动连接)。
更新
尝试从容器内部连接到localhost
将无法工作(postgres不在该容器内运行)。 你将需要使用主机名db
,或者你需要的db
容器的IP地址。 例如:
postgres -h db -U postgres postgres
你可以使用localhost
作为主机名,如果你把db
容器本身运行。