render 是一个 免费、简单、自动部署、自动 HTTPS 的云平台,非常适合 Flask、Django、Node、Go 等后端框架。
my_flask_app/
│── app.py
│── requirements.txt
│── Procfile
└── templates/
└── index.html
撰写 Flask 程式(示例)
app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
return render_template("index.html")
if __name__ == "__main__":
app.run(host="0.0.0.0", port=10000)
⚠ Render 会自动指定 PORT,所以你必须写
host="0.0.0.0"。
建立 HTML 模板(必须放在 templates/)
templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Flask Render Deploy</title>
</head>
<body>
<h1>Hello from Flask on Render!</h1>
</body>
</html>
建立 requirements.txt
使用 pip 导出:
pip freeze > requirements.txt
或手动写:
Flask==3.0.0
gunicorn
gunicorn 是必要的,Render 会用它来执行 Flask。
建立 Procfile
Render 必须知道怎么启动你的 Flask 程式。
Procfile
web: gunicorn app:app
说明:
| 字段 | 意义 |
|---|---|
web: |
Render 的 Web Service |
gunicorn |
WSGI Server |
app:app |
文件名:Flask实例名称 |
上传到 GitHub
Render 只能从 GitHub/GitLab 部署,因此你需要:
git init
git add .
git commit -m "initial commit"
git branch -M main
git remote add origin <你的 GitHub repo 链接>
git push -u origin main
前往 Render.com 部署
- 到 https://render.com/
- 登录(推荐 GitHub 登录)
- 点 “New” → “Web Service”
- 选择你的 GitHub Repository
- 设置参数:
| 项目 | 填写 |
|---|---|
| Environment | Python |
| Build Command | pip install -r requirements.txt |
| Start Command | gunicorn app:app |
按 Create Web Service。
Render 自动部署
接着 Render 会:
- 安装所有套件
- 使用 gunicorn 启动你的 Flask
- 自动提供 HTTPS
- 自动更新你的 Web Service URL
例如:
https://my-flask-app.onrender.com
部署成功后就可以访问网站!
如何修改代码并自动更新?
只要你更新 GitHub:
git add .
git commit -m "update"
git push
Render 会自动触发重新部署。