Docker多阶段构建:如何复制全局nodemon?如何清理installer容器?
Hey there! Let's break down your questions and fix up your Dockerfile step by step.
1. How to copy the globally installed nodemon to your Alpine working container
When you install a package globally with npm install -g, it gets placed in two key locations in the official Node.js image:
- The package files go to
/usr/local/lib/node_modules/nodemon - The executable binary (which lets you run
nodemonfrom the command line) goes to/usr/local/bin/nodemon
To get these into your Alpine container, you just need to add two COPY --from=installer lines to your second stage. Here's the updated Dockerfile with this fix:
# Installer stage - full Node image for dependency installation FROM node:10 as installer WORKDIR /src COPY package.json package-lock.json ./ # Install all project dependencies RUN npm install # Globally install nodemon RUN npm install -g nodemon # Working container - minimal Alpine image FROM node:10-alpine RUN mkdir /src WORKDIR /src # Copy project dependencies from installer stage COPY --from=installer /src/node_modules ./node_modules # Copy globally installed nodemon files COPY --from=installer /usr/local/lib/node_modules/nodemon /usr/local/lib/node_modules/nodemon COPY --from=installer /usr/local/bin/nodemon /usr/local/bin/nodemon # Copy your application code COPY . . EXPOSE 3000 CMD ["nodemon", "start"]
Note: I adjusted the project dependency copy to only grab node_modules instead of the entire /src directory – this avoids overwriting your application code later when you run COPY . ..
2. Do you need to manually remove the "installer" container?
Nope! That's one of the great things about multi-stage builds. Docker automatically discards intermediate stages (like your installer stage) after it builds the final target image. The only way the installer stage would stick around is if you explicitly build it with docker build --target installer . – otherwise, it's just a temporary layer that gets cleaned up automatically. No extra steps needed on your end.
内容的提问来源于stack exchange,提问作者Rolly

