Home > database >  How can I execute a command inside a docker from a node app?
How can I execute a command inside a docker from a node app?

Time:01-19

I have a node app running, and I need to access a command that lives in an alpine docker image. Do I have to use exec inside of javascript? How can I install latex on an alpine container and use it from a node app?

I pulled an alpine docker image, started it and installed latex.

Now I have a docker container running on my host. I want to access this latex compiler from inside my node app (dockerized or not) and be able to compile *.tex files into *.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 e.g. a node app?

CodePudding user response:

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.

For example, this Javascript code will run in any environment that has LaTeX installed locally, Docker or otherwise:

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. You mention using an Alpine-based LaTeX setup, so you could

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. There are several aspects of this that are tricky, including security concerns and managing the input and output files. 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.

  • Related