使用 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 替代方案
  • 内网文件分发服务
相关推荐
Cloud_Shy61811 分钟前
解读《Effective Python 3rd Edition》:从练气到老魔(第五章 Item 33 - 35)
开发语言·人工智能·笔记·python·学习方法
星恒随风16 分钟前
C++ 类和对象入门(五):初始化列表、explicit 和 static 成员详解
开发语言·c++·笔记·学习·状态模式
艾利克斯冰28 分钟前
Java 设计模式-行为型模式(更新中)
java·开发语言·设计模式
倒霉蛋小马41 分钟前
Java新特性:record关键字
java·开发语言
abcy0712131 小时前
python pandas csv异步后台清洗前端优先返回成功信息
前端·python·pandas
budingxiaomoli1 小时前
Spring日志
java·开发语言
牛油果子哥q1 小时前
【C++ STL vector】C++ STL vector 终极精讲:动态数组底层原理、两倍扩容机制、迭代器失效、增删查改、性能剖析与工程避坑指南
开发语言·c++
颜酱1 小时前
LangChain使用RAG 入门:让大模型读懂你的私有文档
python·langchain
贩卖黄昏的熊1 小时前
flex 布局快速梳理
开发语言·javascript·css3·html5
天天进步20152 小时前
Python全栈项目--校园智能宿舍管理系统
开发语言·python