使用 Tornado + systemd 搭建图片静态服务(imgserver)

下面我帮你把这套 Tornado 静态图片服务 + systemd 守护进程 整理成一篇可直接使用的教程,适合放到博客或内部文档里。


使用 Tornado + systemd 搭建图片静态服务(imgserver)

一、环境说明

  • 操作系统:Linux(Ubuntu / CentOS 均可)

  • Python:Python 3

  • Web 框架:Tornado

  • 监听端口:7097

  • 图片目录:

    复制代码
    /www/wwwroot/study_front.kuitao8.com/resources/upload

二、编写 Tornado 静态文件服务

1️⃣ 创建服务脚本

编辑 server.py

bash 复制代码
vim /www/wwwroot/test.example.com/resources/server.py

内容如下:

python 复制代码
from tornado.web import Application
from tornado.ioloop import IOLoop
import tornado.web

def make_app():
    urls = [
        (
            r"/upload/(.*)",
            tornado.web.StaticFileHandler,
            {
                "path": "/www/wwwroot/test.example.com/resources/upload"
            }
        ),
    ]
    return Application(urls)

if __name__ == "__main__":
    app = make_app()
    app.listen(7097)
    IOLoop.instance().start()

2️⃣ 访问示例

假设上传目录下有文件:

复制代码
/www/wwwroot/test.example.com/resources/upload/test.jpg

浏览器访问:

复制代码
http://服务器IP:7097/upload/test.jpg

三、创建 systemd 服务(开机自启)

为了让 Tornado 服务后台运行、自动重启、开机启动,使用 systemd 管理。

1️⃣ 创建服务文件

bash 复制代码
vim /etc/systemd/system/imgserver.service

内容如下:

ini 复制代码
[Unit]
Description=imgserver
After=syslog.target network.target

[Service]
User=root
Environment="PATH=/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/usr/bin/python3"
ExecStart=/usr/bin/python3 /www/wwwroot/test.example.com/resources/server.py
Restart=always
RestartSec=3

[Install]
WantedBy=default.target

💡 说明

  • ExecStart:指定 Python3 和服务脚本路径
  • Restart=always:服务异常退出自动重启
  • User=root:以 root 用户运行(如需更安全可改为普通用户)

四、systemd 服务管理命令

1️⃣ 重新加载 systemd 配置

bash 复制代码
systemctl daemon-reexec
systemctl daemon-reload

2️⃣ 设置开机自启

bash 复制代码
systemctl enable imgserver.service

3️⃣ 启动服务

bash 复制代码
systemctl start imgserver.service

4️⃣ 查看运行状态

bash 复制代码
systemctl status imgserver.service

5️⃣ 重启服务

bash 复制代码
systemctl restart imgserver.service

6️⃣ 停止服务

bash 复制代码
systemctl stop imgserver.service

五、常见问题排查

🔍 1. 端口是否监听成功

bash 复制代码
ss -lntp | grep 7097

🔍 2. 查看日志

bash 复制代码
journalctl -u imgserver.service -f

🔍 3. 目录权限问题

确保 Tornado 进程对图片目录有读取权限:

bash 复制代码
chmod -R 755 /www/wwwroot/test.example.com/resources/upload

六、适用场景

  • 图片 / 文件静态服务
  • 前端上传资源访问
  • 轻量级 CDN 替代方案
  • 内网文件分发服务
相关推荐
IVEN_5 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang7 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮7 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling7 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮10 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽10 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers