1 回复

基于Docker部署Sanic项目,核心是编写正确的Dockerfile和配置。下面是一个完整、可直接使用的示例。

首先,确保你的项目结构类似这样:

my_sanic_app/
├── app.py
├── requirements.txt
└── Dockerfile

1. app.py (你的Sanic应用主文件)

from sanic import Sanic
from sanic.response import text

app = Sanic("MySanicApp")

@app.get("/")
async def hello(request):
    return text("Hello from Sanic in Docker!")

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000, debug=False, access_log=False)

关键点:host必须设为"0.0.0.0",否则容器外无法访问。

2. requirements.txt

sanic>=23.6.0

3. Dockerfile

# 使用官方Python轻量级镜像
FROM python:3.11-slim

# 设置工作目录
WORKDIR /app

# 复制依赖文件并安装
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 复制应用代码
COPY . .

# 暴露端口(Sanic默认8000)
EXPOSE 8000

# 启动命令
CMD ["python", "app.py"]

4. 构建和运行 在项目根目录执行:

# 构建镜像
docker build -t my-sanic-app .

# 运行容器
docker run -d -p 8000:8000 --name sanic-container my-sanic-app

现在访问 http://localhost:8000 就能看到"Hello from Sanic in Docker!"。

要点总结:镜像用slim版减少体积,CMD直接启动app.py,Sanic的host要绑定0.0.0.0。

回到顶部