关于前端:前端nodeweb镜像构建基于Alpine-Linux

4次阅读

共计 2164 个字符,预计需要花费 6 分钟才能阅读完成。

镜像内置 canvas 依赖, 浏览器, 字体包

最近在做 node 截图服务,蕴含 echart 配置项和浏览器截图。在本地环境开发好了之后部署容器发现上面问题

  1. canvas 包装置不上
  2. puppeteer 运行谬误
  3. 没有中文字体包。

接下来一步步解决问题,咱们是 docker 部署,首先须要抉择镜像和编写 Dockerfile(或者流水线构建编辑)

Dockerfile

FROM xx 镜像: 版本
WORKDIR /app
ADD . .
RUN npm i --registry=https://registry.npmmirror.com
EXPOSE 3030
CMD ["sh", "-c", "NODE_ENV=$NODE_ENV node ./app.js"]

镜像

因为乌班图和 CentOS 等系统漏洞太多平安扫描通不过公司不让用,只能应用他们提供的根底镜像, 根底镜像外面什么都没有须要一顿装置

依据 canvas 文档 的形容没有找到前置依赖的文档,导致老是装置报错,通过摸索须要的依赖如下

步骤如下

# 装置图形化软件和编译器用于 canvas 依赖
apk add --update --no-cache make g++ jpeg-dev cairo-dev giflib-dev pango-dev libtool autoconf automake 

# 装置 浏览器 node npm
apk add --update --no-cache chromium nodejs npm

总共装置了 238 个包须要 10 多分钟

装置实现截图发现没有中文字体包,接下来就要把字体包拷贝到容器外面去了。
在另外一个控制台输出上面命令

# mac 字体地址 /System/Library/Fonts 其它本人查找
# 镜像字体库地址 /usr/share/fonts/ 不对本人查找下
# 查看运行的镜像 docker ps 找到须要的 CONTAINER ID
docker cp /System/Library/Fonts/ b0cda85d36:/usr/share/fonts/

而后镜像外面查看一次运行

cd /usr/share/fonts/
ls
mkfontscale
mkfontdir
fc-cache

而后运行看下 fc-list :lang=zh 看下字体包 这样就是 ok 的

在测试浏览器截图的时候有个报错须要看下浏览器地位 找到它

cd /usr/bin
ls

而后批改 js 代码 executablePath 指定一个地址

puppeteer.launch({args: ['--no-sandbox', '--disable-setuid-sandbox'],
    executablePath: '/usr/bin/chromium-browser',
})

下一步新建文件测试

cd /tmp
npm i canvas puppeteer
touch canvas.js
touch puppeteer.js

vi canvas.js
vi puppeteer.js

canvas.js

const fs = require('fs')
const {createCanvas, loadImage} = require('canvas')

const canvas = createCanvas(1200, 500)
const context = canvas.getContext('2d')

context.fillStyle = '#000'
context.fillRect(0, 0, 1200, 500)
context.font = 'bold 70pt Menlo'
context.textAlign = 'center'
context.textBaseline = 'top'
context.fillStyle = '#3574d4'

const text = 'Hello, World! 你好,世界'

const textWidth = context.measureText(text).width
context.fillRect(600 - textWidth / 2 - 10, 170 - 5, textWidth + 20, 120)
context.fillStyle = '#fff'
context.fillText(text, 600, 170)

const buffer = canvas.toBuffer('image/png')
fs.writeFileSync('./canvas.png', buffer)

puppeteer.js

const puppeteer = require("puppeteer");
puppeteer
    .launch({args: ['--no-sandbox', '--disable-setuid-sandbox'],
        executablePath: '/usr/bin/chromium-browser',
     })
    .then(async browser => {const page = await browser.newPage();
      await page.goto("https://www.baidu.com");
      await page.screenshot({path: "puppeteer.png"});
      await browser.close();});

在下一步就是运行测试了

node canvas.js
node puppeteer.js

ls

最初看下这两个图片失常吗

没问题删除测试货色打镜像了

rm -rf /tmp/*

以上是我碰到的问题,有问题欢送探讨和交换。

正文完
 0