Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dockerfile - add node.js via use COPY --from

I can create a docker container with PHP and composer with this:

FROM php:fpm
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

Is there any equivalent way to archive the same for node.js and npm? The only solutions I figured so far are:

  • install it the recommended way (https://github.com/nodesource/distributions/blob/master/README.md)
  • clone via git and install it from there
  • using this method (https://stackoverflow.com/a/61054246)

If I use the last method, the container gets bloated in size as I copy everything over (around 908 MB). So I wonder if there is a smarter way. What folders/files would I have to copy over to just implement node and npm functionality?

like image 347
Wombat98 Avatar asked Mar 31 '26 23:03

Wombat98


2 Answers

For node and npm to work you have to copy two directories in your Dockerfile:

# Get NodeJS
COPY --from=node:20-slim /usr/local/bin /usr/local/bin
# Get npm
COPY --from=node:20-slim /usr/local/lib/node_modules /usr/local/lib/node_modules
like image 60
andreasm Avatar answered Apr 02 '26 13:04

andreasm


I used this:

COPY --from=node:18.16.0-slim /usr/local /usr/local

Update: edited my answer so that copies the whole /usr/local folder instead of only /usr/local/bin. If you want to be more precise and save space (looks like 500MB), see @andreasm 's answer and copy the bin and lib/node_modules folders specifically.

like image 28
veuncent Avatar answered Apr 02 '26 13:04

veuncent