skip to Main Content

I have a Dockerfile that builds some webpack stuff:

FROM node:21 as assets
COPY ...
RUN npm install
RUN npm run build

That produces a dist directory with roughly the following content:

webpack-stats.json
bundle.js
bundle.css

Now i have two Containers that need the result:

FROM python:latest
COPY --from=assets /app/dist/webpack-stats.json .
CMD python ...
FROM nginx:latest
COPY --from=assets /app/dist/ .
CMD nginx ...

However, those can’t be put in the same Dockerfile, since one Dockerfile only builds one image / container.
I also want to avoid running the build container twice to avoid inconsistency and long build times.

Is there a way to built only once, but use it in two containers?

2

Answers


  1. Is there a way to built only once, but use it in two containers?

    So tag it.

    /assets/Dockefile
        FROM node:21 as assets
        COPY ...
        RUN npm install
        RUN npm run build
    /app1/Dockerfile
        FROM assets AS assets
        FROM python:latest
        COPY --from=assets /app/dist/webpack-stats.json .
        CMD python ...
    

    And then build with

    cd assets
    docker build -t assets .
    cd ..
    cd app1
    docker build .
    

    "Professionally" you would publish assets from a separate CI/CD into a private docker repository, like for example to gitlab project container registry, and use the full name in depende dockerfile.

    Login or Signup to reply.
  2. This is why people have Docker Hub accounts. I didn’t try this, just rolled off the fingers.

    In one directory you have Dockerfile containing

    FROM node:21 as assets
    COPY ...
    RUN npm install
    RUN npm run build
    

    Now

    docker login
    docker build --pull -t <yourdockerusername>/mybasebuild .
    docker push <yourdockerusername>/mybasebuild
    

    Now in a different directory you have a Dockerfile containing this

    FROM mybasebuild as Builder
    FROM python:latest
    COPY --from=Builder /app/dist/webpack-stats.json .
    CMD python ...
    

    in case you logged out

    docker login
    docker build --pull -t <yourdockerusername>/mylittlepython .
    docker push <yourdockerusername>/mylittlepython
    

    In a third directory you have a Dockerfile containing this

    FROM mybasebuild as Builder
    FROM nginx:latest
    COPY --from=assets /app/dist/ .
    CMD nginx ...
    

    If you logged out of docker log back in and

    docker build --pull -t <yourdockerusername>/mylittleinx .
    docker push <yourdockerusername>/mylittleinx
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search