dockerize不会延迟容器初始化

时间:2016-10-20 09:35:57

标签: python django postgresql docker

我正在为我的项目准备图像。我使用dockerize来控制我的初始化。我不确定docker给出的IP地址的硬编码是否可行?

问题: backend不会等到database首先完成初始化。

终端说

backend_1      | django.db.utils.OperationalError: could not connect to server: Connection refused
backend_1      |        Is the server running on host "sakahama_db" (172.21.0.2) and accepting
backend_1      |        TCP/IP connections on port 5432?

以下是我的文件:

devdb.dockerfile

FROM postgres:9.5

# Install hstore extension
COPY ./Dockerfiles/hstore.sql /docker-entrypoint-initdb.d

RUN mkdir -p /var/lib/postgresql-static/data
ENV PGDATA /var/lib/postgresql-static/data

hstore.sql

create extension hstore;

backend.dockerfile

FROM python:2

RUN apt-get update && apt-get install -y wget

ENV DOCKERIZE_VERSION v0.2.0
RUN wget https://github.com/jwilder/dockerize/releases/download/$DOCKERIZE_VERSION/dockerize-linux-amd64-$DOCKERIZE_VERSION.tar.gz \
    && tar -C /usr/local/bin -xzvf dockerize-linux-amd64-$DOCKERIZE_VERSION.tar.gz

RUN mkdir /usr/src/app
WORKDIR /usr/src/app

COPY requirements ./requirements
RUN pip install -r requirements/local.txt

COPY . .

EXPOSE 8000

CMD echo "dockerize"
CMD ["dockerize", "-wait", "tcp://sakahama_db:5432"]

CMD echo "migrate"
CMD ["python", "sakahama/manage.py", "migrate"]

CMD echo "runserver"
CMD ["python", "sakahama/manage.py", "runserver", "0.0.0.0:8000"]

搬运工-compose.yml

version: "2"

services:

  backend:
    build:
      context: .
      dockerfile: Dockerfiles/backend.dockerfile
    restart: "always"
    environment:
      DATABASE_URL: postgres://username:password@sakahama_db:5432/sakahama
      REDISCLOUD_URL: redis://redis:6379/0
    links:
      - sakahama_db
    ports:
      - "9000:8000"

  sakahama_db:
    build:
      context: .
      dockerfile: Dockerfiles/devdb.dockerfile
    environment:
      POSTGRES_USER: username
      POSTGRES_PASSWORD: password
      POSTGRES_DB: sakahama
    ports:
      - "5435:5432"

  redis:
    image: redis
    expose:
      - "6379"

问题:如何正确使用dockerize

更新
我试过像这样的临时解决方案。但它不起作用 backend-entrypoint.sh

#!/bin/bash
echo "dockerize"
dockerize -wait tcp://sakahama_db:5432

echo "migrate"
python sakahama/manage.py migrate

echo "runserver"
python sakahama/manage.py runserver 0.0.0.0:8000

和docker-compose.yml:
我添加一行 command: ["sh", "Dockerfiles/backend-entrypoint.sh"]

1 个答案:

答案 0 :(得分:1)

当你的Postgres容器启动时,它开始接收你使用命令dockerize -wait tcp://sakahama_db:5432 发送的tcp包,但这并不意味着Postgres服务已准备就绪。加载,设置用户,密码,创建数据库或加载数据库并进行所需的所有授权需要一些时间。

我在Flask和MySQL上遇到了类似的问题,我创建了一个像你一样的sh脚本,在里面我创建了一个简单的循环来检查服务是否在启动Flask应用程序之前

我不是一个shell脚本高级,但这里遵循脚本:

# testing if databas is up
mysql -h database -uroot -proot databasename
ISDBUP=$?
while [[ $ISDBUP != "0" ]]; do
    echo "database is not up yet, waiting for 5 seconds"
    sleep 5;
    mysql -h database -uroot -proot databasename -e "SELECT 1;";
    ISDBUP=$?
done

# starting the application
python server.py app