在运行Ubuntu 18.04的Docker容器上安装字体

我正在尝试在运行Ubuntu 18.04的Docker容器中安装字体(Dockerfile继承自Jupyter scipy笔记本,该笔记本又继承自基础jupyter镜像,Dockerfile链接在这里)。

我尝试了很多不同的方法,包括这个答案和其中的其他建议。

我的Dockerfile如下:

FROM jupyter/scipy-notebook

USER root

# bash instead of dash to use source
RUN ln -snf /bin/bash /bin/sh

# These require sudo so they must come before defining
# a user

# Font attempt
COPY GillSansMTPro-Medium.otf /usr/local/share/fonts
RUN fc-cache -f -v

# installing some pip packages

当我尝试在matplotlib中使用这个字体时,我看到了这个错误: error message 我已经尝试添加

RUN rm -fr ~/.cache/matplotlib

在我的 Dockerfile 中(在上面显示的部分之后)添加了这一行,因为我在线上读到说它可能解决问题。但是它也没有起作用。

另外,如果我导航到/usr/local/share/fonts,我可以看到预期的字体。

有任何解决办法吗?

2个回答

我之前也遇到过和你一样的情况。
这是我的Docker文件。希望能对你有所帮助。
FROM jupyter/scipy-notebook

# create directory for cuistom.css and copy it.
RUN mkdir -p /home/jovyan/.jupyter/custom
COPY custom.css /home/jovyan/.jupyter/custom

# create font directory and copy the font
RUN mkdir -p /home/jovyan/.fonts
COPY D2Coding.ttf /home/jovyan/.fonts
COPY D2CodingBold.ttf /home/jovyan/.fonts

# refresh system font cache
RUN fc-cache -f -v

# refresh matplotlib font cache
RUN rm -fr ~/.cache/matplotlib

在我的情况下,它有效果。

我在一个运行在Docker容器中的Java服务中遇到了类似的问题,即使用自定义字体的问题。基本上,有两种设置方式:

  1. 在构建镜像时将字体放入其中,
  2. 在启动容器时附加一个包含字体的卷;

如果您计划重用容器来运行需要字体的不同应用程序,则第一种方法很有用。对于后一种方法,您可以准备好环境(例如测试或生产环境),然后在不需要重新构建它们的情况下,在不同的Docker容器之间共享字体,甚至是第三方容器。

以下是一个示例,演示如何准备环境,然后临时附加字体:

$ wget https://www.paratype.ru/uni/public/PTSans.zip \
 -O ~/.fonts/PTSans.zip
$ cd ~/.fonts 
$ unzip PTSans.zip
$ sudo cp -rfv .fonts /usr/share/fonts/
$ cd /usr/share/fonts/
$ sudo mv .fonts/ pt_sans/
$ cd pt_sans
$ fc-cache -fv
$ docker run -d --name reports \
  -v /usr/share/fonts/pt_sans:/usr/share/fonts/pt_sans \
  your-container/reports

请确保您根据您的情况更新了相关名称。
这篇文章中有更多详细信息描述。