问题描述
我正在尝试创建一个用Python Flask编写,由gunicorn运行,然后被docker化的新应用.
I am trying to create a new app that is written in Python Flask, run by gunicorn and then dockerised.
我遇到的问题是docker容器内的性能非常差,不一致,最终我得到了响应,但我不明白为什么性能会下降.有时我在日志[CRITICAL] WORKER TIMEOUT (pid:9)
中看到.
The problem I have is the performance inside the docker container is very poor, inconsistent and I do eventually get a response but I can't understand why the performance is decreasing. Sometimes I see in the logs [CRITICAL] WORKER TIMEOUT (pid:9)
.
这是我的应用程序:
server.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "The server is running!"
if __name__ == '__main__':
app.run()
Dockerfile
FROM python:3.6.9-slim
# Copy all the files to the src folder
COPY build/ /usr/src/
# Create the virtual environment
RUN python3 -m venv /usr/src/myapp_venv
# Install the requirements
RUN /usr/src/myapp_venv/bin/pip3 install -r /usr/src/requirements.txt
# Runs gunicorn
# --chdir sets the directory where gunicorn should look for the server files
# server:app means run the "server.py" file and look for the "app" constructor within that
ENTRYPOINT ["/usr/src/myapp/bin/gunicorn", "--bind", "0.0.0.0:5000", "--workers", "1", "--chdir", "/usr/src/", "server:app"]
# Expose the gunicorn port
EXPOSE 5000
requirements.txt
Click==7.0
Flask==1.1.1
gunicorn==20.0.0
itsdangerous==1.1.0
Jinja2==2.10.3
MarkupSafe==1.1.1
Werkzeug==0.16.0
我这样运行docker容器:
I run the docker container like this:
docker build -t killerkode/myapp .
docker run --name myapp -p 5000:5000 killerkode/myapp
推荐答案
我设法找到了这篇有用的文章,该文章解释了Gunicorn为何挂起. https://pythonspeed.com/articles/gunicorn-in-docker/
I managed to find this helpful article which explains why Gunicorn hangs.https://pythonspeed.com/articles/gunicorn-in-docker/
对我来说,解决方案是更改worker临时目录,并将最小worker增加到2.我仍然看到worker被杀死了,但是不再有任何延迟/缓慢.我怀疑添加gthread
会进一步改善效果.
The solution for me was to change the worker temp directory and increase the minimum workers to 2. I still see workers being killed off but there is no longer any delays / slowness. I suspect adding in the gthread
will improve things further.
这是我更新的Dockerfile:
Here is my updated Dockerfile:
FROM python:3.6.9-slim
# Copy all the files to the src folder
COPY build/ /usr/src/
# Create the virtual environment
RUN python3 -m venv /usr/src/myapp_venv
# Install the requirements
RUN /usr/src/myapp_venv/bin/pip3 install -r /usr/src/requirements.txt
# Runs gunicorn
# --chdir sets the directory where gunicorn should look for the server files
# server:app means run the "server.py" file and look for the "app" constructor within that
ENTRYPOINT ["/usr/src/myapp/bin/gunicorn", "--bind", "0.0.0.0:5000", "--worker-tmp-dir", "/dev/shm", "--workers", "2", "--chdir", "/usr/src/", "server:app"]
# Expose the gunicorn port
EXPOSE 5000
这篇关于Docker:通过Gunicorn运行Flask应用-工人超时吗?表现不佳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!