如何利用FROM导入本地其他目录Dockerfile,实现Docker多阶段构建?
Great question! Let’s break down your two core questions clearly:
1. Can FROM directly reference a Dockerfile in another local directory?
No, Docker’s FROM directive can’t point directly to a Dockerfile path—it only accepts the name (or ID) of an already-built image (either local or from a remote registry).
If you want to reuse the build logic from a Dockerfile in another directory, here are two practical workarounds:
- First build that directory’s Dockerfile into a named image, then reference it in your multi-stage build:
Then in your main Dockerfile:# Build the external stage into a local image first docker build -t my-shared-builder ./path/to/other/directoryFROM my-shared-builder as builder # Use artifacts from this stage in subsequent steps FROM alpine:latest COPY --from=builder /app/dist /usr/local/app CMD ["/usr/local/app/start"] - Use the
docker buildcommand’s-fflag to specify the external Dockerfile during a multi-stage build, paired with--targetif you only need a specific stage from it.
2. Can I add other Dockerfiles to the current build and use FROM with them?
You can’t "import" a Dockerfile into another one by copying it with ADD/COPY and expecting FROM to execute its content—ADD only places the Dockerfile as a static file inside the image, not as executable build instructions.
Instead, the standard approach is to integrate the content of the external Dockerfiles directly into your main multi-stage Dockerfile. For example:
Suppose you have a backend/Dockerfile with:
FROM python:3.11 WORKDIR /backend ADD requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt ADD . ./ RUN python manage.py collectstatic
And a frontend/Dockerfile that needs to use backend assets, you can merge them into a single multi-stage Dockerfile:
# Stage 1: Reuse logic from backend/Dockerfile FROM python:3.11 as backend-builder WORKDIR /backend ADD ./backend/requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt ADD ./backend/ ./ RUN python manage.py collectstatic # Stage 2: Your final frontend image FROM nginx:alpine COPY --from=backend-builder /backend/static /usr/share/nginx/html/static ADD ./frontend/dist /usr/share/nginx/html EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]
If you want to keep Dockerfiles separate but automate the chained build, you can write a simple shell script to build each stage in order and pass artifacts between them.
内容的提问来源于stack exchange,提问作者Baily

