ffmpeg功能融入docker容器
一、引言
| 之前已经在linux服务器上安装ffmpeg并封装为mcp工具(详情见[linux服务器安装ffmpeg并封装为mcp工具 | ~吴 银 双~](https://www.wuyinshuang.com/posts/ffmpeg-mcp-tool/))。后来在实际部署过程中,由于应用是docker部署,总是找不到ffmpeg执行路径,干脆直接封装在项目里。 |
二、具体内容
1.准备条件
下载ffmpeg-7.0.2stati压缩包并放到项目的根目录下(ffmpeg-7.0.2stati目录与src目录同级)。
2.修改Dockerfile文件映射
在Dockerfile文件中增加以下内容:
1
2
3
4
5
6
#复制ffmpeg执行文件到容器中
COPY./ffmpeg-7.0.2static/ffmpeg /usr/local/bin/
COPY./ffmpeg-7.0.2static/ffprobe /usr/loca1/bin/
#添加执行权限
RUN chmod +x /usr/local/bin/ffmpeg /usr/local/bin/ffprobe
3.java代码调用ffmpeg命令
ffmpeg执行路径即为上面写的/usr/local/bin/ffmpeg
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
30
31
32
33
34
35
36
String ffmpegPath = "/usr/local/bin/ffmpeg";
//拼装并执行ffmpeg命令
private int runFfmpeg(File inputFile, File outputFile)throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder (
ffmpegPath,
"-i", inputFile.getAbsolutePath();
"-vn"
);
//覆盖已存在输出文件
pb.command().add ("-y").
pb.command().add (outputFile.getAbsolutePath());
pb.redirectErrorStream(true);
Process process = pb.start();
//读取输出日志,防止缓冲区阻塞
StringBuilder outputLog = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader (process.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null){
outputLog.append(line).append("\n");
if (line.contains("frame=") || line.contains("time=")) {
log.info("ffmpeg进度:"+line.trim();
}
}
}
boolean completed = process.waitFor(TIMEOUT_SECONDS, TimeUnit.SECONDS);
if (!completed) {
process.destroyForcibly();
throw new IOException("ffmpeg执行超时(超过"+TIMEOUT_SECONDS+"秒)");
}
int exitCode = process.exitValue();
if (exitCode != 0) {
String erroeMessage = extractErrorMessage(OutputLog.toString);
}
return exitCode ;
}
三、总结
Dockerfile把ffmpeg静态文件直接复制进镜像,比较方便。后续即便是双活服务器迁移更换,也不影响ffmpeg功能使用。
作者:吴银双
日期:2026年8月4日
平台:GitHub Pages / 技术博客
本文由作者按照 CC BY 4.0 进行授权