Docker Cloud自动testing找不到服务
我目前正在试图dockerize我的一个Django API项目。 它使用postgres作为数据库。 我使用Docker Cloud作为CI,以便可以构build,皮棉和运行testing。
我从下面的DockerFile开始
# Start with a python 3.6 image FROM python:3.6 ENV PYTHONUNBUFFERED 1 ENV POSTGRES_USER postgres ENV POSTGRES_PASSWORD xxx ENV DB_HOST db RUN mkdir /code ADD . /code/ WORKDIR /code RUN pip install -r requirements.txt RUN pylint **/*.py # First tried running tests from here. RUN python3 src/manage.py test
但是这个DockerFile总是失败,因为在运行unit testing时Django不能连接到任何数据库,并且由于没有postgres实例在这个Dockerfile中运行
django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known
然后,我在Docker Cloud中发现了一个名为“Autotest”的东西,它允许您使用docker-compose.text.yml文件来描述堆栈,然后在每个版本中运行一些命令。 这似乎是我运行testing所需要的,因为它可以让我构build我的Django镜像,引用已经存在的postgres镜像并运行testing。
我删除了
RUN python3 src/manage.py test
从DockerFile中创build了以下docker-compose.test.yml文件。
version: '3.2' services: db: image: postgres:9.6.3 environment: - POSTGRES_USER=$POSTGRES_USER - POSTGRES_PASSWORD=$POSTGRES_PASSWORD sut: build: . command: python src/manage.py test environment: - POSTGRES_USER=$POSTGRES_USER - POSTGRES_PASSWORD=$POSTGRES_PASSWORD - DB_HOST=db depends_on: - db
然后当我跑步
docker-compose -f docker-compose.test.yml build
和
docker-compose -f docker-compose.test.yml run sut
本地testing全部运行,全部通过。
然后,我将我的更改推送到Github,Docker云构build它。 构build本身成功,但使用docker-compose.test.yml文件的自动testing失败,并显示以下错误:
django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "db" (172.18.0.2) and accepting TCP/IP connections on port 5432?
因此,似乎数据库服务没有启动,或者在我的本地机器上启动Docker Cloud的速度太慢了?
谷歌了一下,我发现这个https://docs.docker.com/compose/startup-order/它说,容器不真的等待对方是100%准备。 然后他们build议编写一个包装脚本来等待postgres,如果真的需要的话。
我遵循他们的指示,并使用wait-for-postgres.sh脚本。
多汁部分:
until psql -h "$host" -U "postgres" -c '\l'; do >&2 echo "Postgres is unavailable - sleeping" sleep 1 done
并从我的docker-compose.test.yml中取代了这个命令
command: python src/manage.py test
至
command: ["./wait-for-postgres.sh", "db", "python", "src/manage.py", "test"]
然后我推到Github,Docker Cloud开始build设。 构build图像的作品,但现在自动testing只是等待postgres永远(我等了10分钟,然后手动closuresDocker云中的构build过程)
今天我有了Google-d,看起来像大多数“Dockerize Django”教程都没有提到unit testing。
我使用Docker运行Djangounit testing完全错误吗?
对我来说似乎很奇怪,它在本地运行得非常好,但是当Docker Cloud运行它时,它会失败!
我似乎通过将文件中的docker-compose版本从3.2降级到2.1并使用健康检查来修复它。
healthcheck选项在depends_on子句中给我一个语法错误,因为您必须将数组传递给它。 不知道为什么这不支持在3.2版本
但是这里是我的新docker-compose.test.yml
version: '2.1' services: db: image: postgres:9.6.3 environment: - POSTGRES_USER=$POSTGRES_USER - POSTGRES_PASSWORD=$POSTGRES_PASSWORD healthcheck: test: ["CMD-SHELL", "psql -h 'localhost' -U 'postgres' -c '\\l'"] interval: 30s timeout: 30s retries: 3 sut: build: . command: python3 src/manage.py test environment: - POSTGRES_USER=$POSTGRES_USER - POSTGRES_PASSWORD=$POSTGRES_PASSWORD - DB_HOST=db depends_on: // Does not work in 3.2 db: condition: service_healthy