运行 带有 scratch Docker 图像的 NodeJs 二进制文件

Running NodeJs binary with scratch Docker image

我们可以使用 pkg package 将 NodeJs 应用程序转换为二进制文件。我想构建与 Docker scratch 图像相同的二进制文件和 运行。

index.js

const http = require('http')
http.createServer().listen(3000)

Dockerfile

FROM node:10 as build

COPY index.js .
RUN npm i pkg -g && pkg -t node10-alpine-x64 index.js

FROM scratch
COPY --from=build index /index

ENTRYPOINT ["/index"]

当我 运行 docker build -t index . && docker run --rm -it index 时,我收到此错误消息 - standard_init_linux.go:211: exec user process caused "no such file or directory"

我错过了什么?

scratch 是一个没有任何文件的空图像,您的二进制文件可能具有依赖项并期望某些 linux 环境。尝试使用最少的 linux 基本图像而不是从头开始 - alpinedebianubuntu.

我认为@Isanych 是对的,因为 scratch 对 运行 c++ 很好,去二进制文件但我没有找到 运行 pkg 可执行文件的方法在 scratch 图像上,所以这里是基于 alpine 的解决方案,但 alpine 仍然需要一些提到的依赖项 here,它正在使用下面的图像

你可以试试这个

FROM node:10 as build
WORKDIR /app
COPY index.js .
RUN npm i pkg -g
RUN pkg -t node10-alpine-x64 index.js
FROM alpine
RUN apk add --no-cache libstdc++ libgcc
WORKDIR /app
COPY --from=build /app/ .
CMD ["./index"]

奖励:您的图像仍低于 50 MB。

您可以使用像 https://github.com/astefanutti/scratch-node 这样的 distroless Node.js 图像作为基础图像,例如:

FROM node as builder
WORKDIR /app
COPY package.json package-lock.json index.js ./
RUN npm install --prod

FROM astefanutti/scratch-node
COPY --from=builder /app /
ENTRYPOINT ["node", "index.js"]

Node 16 基本映像的大小压缩后为 17.1 MB。