在 docker 更改后重新启动 Flask 应用程序

Restart flask app in docker on changes

我正在使用 flask-script 运行 我的应用程序:

if __name__ == "__main__":
    manager.run()

在 docker 我有以下内容:

CMD [ "python", "manage.py", "runserver", "-h", "0.0.0.0", "-p", "5000"]

现在,当我构建 运行 我的容器时,应用 运行 没问题。但是,如果我对我的代码进行更改并保存,尽管我的环境设置了 DEBUG=True 变量,但应用程序不会重新启动。我在这里遗漏了什么吗?

Docker 文件:

FROM python:3.4-slim

RUN apt-get update -y && \
    apt-get install -y \
        python-pip \
        python-dev \
        pkg-config \
        libpq-dev \
        libfreetype6-dev

COPY ./requirements.txt /app/requirements.txt

WORKDIR /app

RUN pip3 install -r requirements.txt

COPY . /app

CMD [ "python", "manage.py", "runserver"]

COPY指令

copies new files or directories from <src> and adds them to the filesystem of the container at the path <dest>.

这意味着映像具有构建映像时文件的快照。当您从该图像启动容器时,它将在其文件系统中看到您的文件副本。修改原始文件不会对容器内的副本产生任何影响,应用程序不会看到这些更改,也不会重新启动。


如果您希望容器内的文件发生变化,您可以mount a host directory as a volume。也来自文档

This command mounts the host directory, /src/webapp, into the container at /webapp. If the path /webapp already exists inside the container’s image, the /src/webapp mount overlays but does not remove the pre-existing content. Once the mount is removed, the content is accessible again.

Docker 运行 命令可能看起来像这样

docker run -d -v /absolute/path/to/src:/app <image-name>

然后你的文件更改应该反映在容器内的文件中(因为它们将是相同的文件)并且一切都应该按预期重新启动。


您可能也对此感兴趣 post Dockerize a Flask, Celery, and Redis Application with Docker Compose。它更进一步,使用 Docker Compose 编排 Flask 开发环境。