GitHub 仓库

上游 README 当前提供 neixin/random-pic-api:latest 镜像,容器监听 80 端口,并从 /var/www/html/portrait、/var/www/html/landscape 递归读取图片。本文只把图片目录挂载到应用要求的子路径,不覆盖容器程序目录。

创建目录和 Compose

1
2
mkdir app && cd app
mkdir -p photos/portrait photos/landscape
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
services:
  random-api:
    image: neixin/random-pic-api:latest # 发布前核对版本或 digest
    container_name: random-pic-api
    restart: unless-stopped
    ports:
      - "127.0.0.1:8080:80"
    volumes:
      - ./photos/portrait:/var/www/html/portrait:ro
      - ./photos/landscape:/var/www/html/landscape:ro

需要公网直连时才将绑定改为 0.0.0.0:8080:80,并在防火墙、限流和反向代理层进行控制。只读挂载可避免应用进程修改图片源。

启动和验证

1
2
3
4
docker compose up -d
docker compose ps
curl -I http://127.0.0.1:8080/random
docker compose logs --tail=100 random-api

若上游版本使用不同的路由,以仓库 README 为准;不要仅凭 HTTP 状态码判断返回内容是否为图片。

图片转换脚本

下面脚本保留目录结构,按大小写不敏感的扩展名筛选,使用相对路径避免同名文件冲突,显式设置 WebP 质量,并汇总失败项。它只写入新的输出目录,不覆盖源文件。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from pathlib import Path
from PIL import Image

SUPPORTED = {".jpg", ".jpeg", ".png", ".gif", ".webp"}

def convert_tree(source: Path, destination: Path, quality: int = 82) -> list[str]:
    destination.mkdir(parents=True, exist_ok=True)
    failures: list[str] = []
    for image_path in source.rglob("*"):
        if not image_path.is_file() or image_path.suffix.lower() not in SUPPORTED:
            continue
        try:
            with Image.open(image_path) as image:
                width, height = image.size
                category = "landscape" if width > height else "portrait"
                relative = image_path.relative_to(source)
                output = destination / category / relative.with_suffix(".webp")
                output.parent.mkdir(parents=True, exist_ok=True)
                image.convert("RGB").save(output, "WEBP", quality=quality, method=6)
        except Exception as error:
            failures.append(f"{image_path}: {error}")
    return failures

failures = convert_tree(Path("/srv/input"), Path("/srv/output"))
if failures:
    print("Conversion failures:")
    print("\n".join(failures))
    raise SystemExit(1)
print("Conversion completed without failures.")

先创建 /srv/output 的父目录并在虚拟环境中安装 Pillow;quality=82 是明确的有损 WebP 示例,若图片内容需要无损保存,应改用适合的参数并验证文件大小和视觉质量。运行前确认输入输出不是同一目录。

备份、更新和反代

图片源才是本服务的主要数据,备份 photos 和 Compose 文件:

1
2
3
docker compose stop
tar -czf ../random-pic-api-backup-$(date +%F).tgz photos compose.yaml
docker compose start

更新前备份图片源、记录旧镜像标签,再执行 docker compose pull && docker compose up -d。出现不兼容时恢复旧标签并重新创建容器,不要删除图片目录。反向代理上游使用 http://127.0.0.1:8080,由代理负责 HTTPS、缓存和访问限制。

来源和限制

仓库、README、Docker Hub 镜像页面请求通过本地代理返回 HTTP 200。本文未启动容器,也未验证当前 latest 的 digest、实际路由或 PHP 运行时行为;生产环境应先核对镜像发布页并固定版本。