相关链接
1.https://docs.docker.com/reference/samples/flask/ (docker 部署使用 Gunicore部署Flask)
2.https://flask.palletsprojects.com/en/stable/deploying/gunicorn/ (Gunicorn部署 Flask)
3.https://flask.palletsprojects.com/en/stable/tutorial/views/ (Flask Blueprints)
项目结构
app.py
import os
from dotenv import load_dotenv, find_dotenv
from flask import Flask, jsonify
from web import index, user
def loadConfig():
# 加载 .env 文件
load_dotenv() # 默认加载当前目录下的 .env 文件
activeFile = os.environ.get("active.file")
if activeFile is not None:
fileName = ".env."f'{activeFile}'
path = find_dotenv(fileName)
# load_dotenv(dotenv_path=".env.prod") # 加载指定路径的 .env 文件
load_dotenv(dotenv_path=path)
def create_app():
loadConfig()
# create and configure the app, instance_relative_config设置true无法找到其他的python web文件
app = Flask(__name__, instance_relative_config=False)
# ensure the instance folder exists
# try:
# os.makedirs(app.instance_path)
# except OSError:
# pass
# a simple page that says hello
@app.route('/hello')
def hello():
return 'Hello World!'
@app.errorhandler(404)
def resource_not_found(e):
return jsonify(error=str(e)), 404
# 注册其他web文件,没有的话,可以注释掉
app.register_blueprint(user.bp)
app.register_blueprint(index.bp)
app.add_url_rule("/", endpoint="index")
return app
Dockerfile
FROM python:3.9.2-alpine
# upgrade pip
RUN pip install --upgrade pip
# get curl for healthchecks
# RUN apk add curl
# permissions and nonroot user for tightened security
RUN adduser -D nonroot
RUN mkdir /home/app/ && chown -R nonroot:nonroot /home/app
RUN mkdir -p /var/log/flask-app && touch /var/log/flask-app/flask-app.err.log && touch /var/log/flask-app/flask-app.out.log
RUN chown -R nonroot:nonroot /var/log/flask-app
WORKDIR /home/app
USER nonroot
# copy all the files to the container
COPY --chown=nonroot:nonroot . .
# venv
ENV VIRTUAL_ENV=/home/app/venv
# python setup
RUN python -m venv $VIRTUAL_ENV
ENV PATH="$VIRTUAL_ENV/bin:$PATH"
RUN export FLASK_APP=app.py
RUN pip install -r requirements.txt
docker-compose.yml
services:
flask-app-1:
build: ../flaskr
image: demo:1.0.0
ports:
- '8000:8000'
# healthcheck:
# test: ["CMD-SHELL", "curl --silent --fail localhost:8000/flask-health-check || exit 1"]
# interval: 10s
# timeout: 10s
# retries: 3
# app为启动入口python文件,create_app()为创建Flask的app方法,可以直接使用声明的Flask的变量,具体内容详情见相关链接2
command: gunicorn -w 3 -t 10 -b 0.0.0.0:8000 'app:create_app()'
requirements.txt
blinker==1.9.0
click==8.1.7
colorama==0.4.6
Flask==3.1.0
gunicorn==23.0.0
itsdangerous==2.2.0
Jinja2==3.1.5
MarkupSafe==3.0.2
packaging==24.2
python-dotenv==0.21.0
setuptools==75.1.0
Werkzeug==3.1.3
wheel==0.44.0
本地调试 wsgi.py 文件
from app import create_app
import os
if __name__ == "__main__":
create_app().run(host='0.0.0.0', port=os.environ.get("FLASK_SERVER_PORT") or 8080, debug=True)