使用 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 替代方案
  • 内网文件分发服务
相关推荐
SelectDB11 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码19 小时前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵1 天前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li1 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸1 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学2 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田2 天前
Pydantic校验配置文件
python
hboot2 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi3 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi3 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab