镜像内置canvas依赖,浏览器,字体包
最近在做node截图服务,蕴含echart配置项和浏览器截图。在本地环境开发好了之后部署容器发现上面问题
- canvas包装置不上
- puppeteer运行谬误
- 没有中文字体包。
接下来一步步解决问题,咱们是docker部署, 首先须要抉择镜像和编写Dockerfile(或者流水线构建编辑)
Dockerfile
FROM xx镜像:版本WORKDIR /appADD . .RUN npm i --registry=https://registry.npmmirror.comEXPOSE 3030CMD ["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 npmapk add --update --no-cache chromium nodejs npm
总共装置了238个包须要10多分钟
装置实现截图发现没有中文字体包,接下来就要把字体包拷贝到容器外面去了。
在另外一个控制台输出上面命令
# mac 字体地址 /System/Library/Fonts 其它本人查找# 镜像字体库地址 /usr/share/fonts/ 不对本人查找下# 查看运行的镜像 docker ps 找到须要的 CONTAINER IDdocker cp /System/Library/Fonts/ b0cda85d36:/usr/share/fonts/
而后镜像外面查看一次运行
cd /usr/share/fonts/lsmkfontscalemkfontdirfc-cache
而后运行看下 fc-list :lang=zh
看下字体包 这样就是ok的
在测试浏览器截图的时候有个报错须要看下浏览器地位 找到它
cd /usr/binls
而后批改js代码 executablePath
指定一个地址
puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'], executablePath: '/usr/bin/chromium-browser',})
下一步新建文件测试
cd /tmpnpm i canvas puppeteertouch canvas.jstouch puppeteer.jsvi canvas.jsvi 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).widthcontext.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.jsnode puppeteer.jsls
最初看下这两个图片失常吗
没问题删除测试货色打镜像了
rm -rf /tmp/*
以上是我碰到的问题,有问题欢送探讨和交换。