首页 > 解决方案 > Heroku 上带有容器注册表的发布阶段运行容器

问题描述

我用 docker 在 Django 中创建了一个简单的项目。根据heroku关于容器注册表发布阶段的文档(https://devcenter.heroku.com/articles/container-registry-and-runtime#release-phase),我创建了一个带有postgres插件的新应用程序。要使用 docker 部署应用程序,我执行了以下命令:

heroku container:push web
heroku container:push release
heroku container:release web release

但是在最后一个命令之后,我的终端被阻塞了,看起来发布阶段实际上运行了一个容器。

Releasing images web,release to teleagh... done
Running release command...
[2019-12-30 21:22:00 +0000] [17] [INFO] Starting gunicorn 19.9.0
[2019-12-30 21:22:00 +0000] [17] [INFO] Listening at: http://0.0.0.0:5519 (17)
[2019-12-30 21:22:00 +0000] [17] [INFO] Using worker: sync
[2019-12-30 21:22:00 +0000] [27] [INFO] Booting worker with pid: 27

我的目标是在发布之前运行 django 迁移。我真的很感激任何帮助。

档案:

release: python manage.py migrate

Dockerfile:

FROM python:3.7-slim

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
ENV PORT=8000
WORKDIR /app
ADD requirements.txt .
RUN pip install -r requirements.txt
RUN apt-get update && apt-get install -y curl
ADD . ./
RUN python manage.py collectstatic --noinput
CMD gunicorn --bind 0.0.0.0:$PORT teleagh.wsgi 

标签: djangodockerheroku

解决方案


在 heroku 中使用容器部署时,Procfile 不生效。如果您想设置发布阶段命令,我可以建议两个我已经测试过很多的选项:

1.为每个阶段创建专用的 Dockerfile,扩展名与阶段名称匹配。

Dockerfile.web

FROM python:3.7-slim

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
ENV PORT=8000
WORKDIR /app
ADD requirements.txt .
RUN pip install -r requirements.txt
RUN apt-get update && apt-get install -y curl
ADD . ./
RUN python manage.py collectstatic --noinput
CMD gunicorn --bind 0.0.0.0:$PORT teleagh.wsgi 

Dockerfile.release

FROM python:3.7-slim

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
ENV PORT=8000
WORKDIR /app
ADD requirements.txt .
RUN pip install -r requirements.txt
RUN apt-get update && apt-get install -y curl
ADD . ./
RUN python manage.py collectstatic --noinput
CMD python manage.py migrate

部署过程看起来和你的一样,除了一个例外——推送命令必须有额外的参数--recursive。此外,可以在一个命令中推送所有容器:

heroku container:push web release --recursive
heroku container:release web release

2.创建一个 bash 脚本来检测容器中当前正在运行的阶段。

启动.sh

#!/bin/bash

if [ -z "$SSH_CLIENT" ] && [ -n "$HEROKU_EXEC_URL" ];
then
    source <(curl --fail --retry 3 -sSL "$HEROKU_EXEC_URL")
fi

if [[ "$DYNO" =~ ^release.* ]];
then
    set -e
    python3 manage.py migrate
else
    exec gunicorn teleagh.wsgi  -b 0.0.0.0:${PORT} --reload --access-logfile -
fi

然后唯一的Dockerfile将如下所示:

FROM python:3.7-slim

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
ENV PORT=8000
WORKDIR /app
ADD requirements.txt .
RUN pip install -r requirements.txt
RUN apt-get update && apt-get install -y curl
ADD . ./
RUN python manage.py collectstatic --noinput
CMD ./start.sh 

希望这会有所帮助


推荐阅读