简体   繁体   English

如何从节点应用程序在 docker 中执行命令?

[英]How can I execute a command inside a docker from a node app?

I have a node app running, and I need to access a command that lives in an alpine docker image.我有一个正在运行的节点应用程序,我需要访问位于高山 docker 图像中的命令。 Do I have to use exec inside of javascript?我必须在 javascript 中使用 exec 吗? How can I install latex on an alpine container and use it from a node app?如何在高山容器上安装 latex 并从节点应用程序使用它?

I pulled an alpine docker image, started it and installed latex .我拉了一个高山 docker 图像,启动它并安装了latex

Now I have a docker container running on my host.现在我的主机上运行了一个 docker 容器。 I want to access this latex compiler from inside my node app (dockerized or not) and be able to compile *.tex files into *.pdf我想从我的节点应用程序内部访问这个 latex 编译器(dockerized 与否)并且能够将 *.tex 文件编译成 *.pdf

If I sh into the alpine image I can compile '.tex into *.pdf just fine, but how can I access this software from outside the container eg a node app?如果我进入 alpine 图像,我可以将 '.tex 编译成 *.pdf 就好了,但是我如何从容器外部访问这个软件,例如节点应用程序?

If you just want to run the LaTeX engine over files that you have in your local container filesystem, you should install it directly in your image and run it as an ordinary subprocess.如果您只想在本地容器文件系统中的文件上运行 LaTeX 引擎,您应该将其直接安装在您的映像中并作为普通子进程运行。

For example, this Javascript code will run in any environment that has LaTeX installed locally, Docker or otherwise:例如,此 Javascript 代码将在本地安装了 LaTeX、Docker 或其他环境的任何环境中运行:

const { execFileSync } = require('node:child_process');
const { mkdtemp, open } = require('node:fs/promises');

const tmpdir = await mkdtemp('/tmp/latex-');
let input;
try {
  input = await open(tmpdir + '/input.tex', 'w');
  await input.write('\\begin{document}\n...\n\\end{document}\n');
} finally {
  input?.close();
}

execFileSync('pdflatex', ['input'], { cwd: tmpdir, stdio: 'inherit' });
// produces tmpdir + '/input.pdf'

In a Docker context, you'd have to make sure LaTeX is installed in the same image as your Node application.在 Docker 上下文中,您必须确保 LaTeX 安装在与您的 Node 应用程序相同的映像中。 You mention using an Alpine-based LaTeX setup, so you could你提到使用基于 Alpine 的 LaTeX 设置,所以你可以

FROM node:lts-alpine
RUN apk add texlive-full # or maybe a smaller subset
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY ./ ./
CMD ["node", "main.js"]

You should not try to directly run commands in other Docker containers.您不应尝试直接在其他 Docker 容器中运行命令。 There are several aspects of this that are tricky, including security concerns and managing the input and output files.这有几个方面很棘手,包括安全问题和管理输入和 output 文件。 If it's possible to directly invoke a command in a new or existing container, it's also very straightforward to use that permission to compromise the entire host.如果可以在新的或现有的容器中直接调用命令,那么使用该权限来破坏整个主机也是非常简单的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM