Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using shared dockerfile for multiple dockerfiles

What I have, are multi similar and simple dockerfiles

But what I want is to have a single base dockerfile and my dockerfiles pass their variables into it.

In my case the only difference between dockerfiles are simply their EXPOSE, so I think it's better to keep a base dockerfile and other dockerfiles only inject that variables into base dockerfile like a template engine

A sample dockerfile:

FROM golang:1.17 AS builder
WORKDIR /app
COPY . .
RUN go mod download
RUN go build -o /bin/app ./cmd/root.go

FROM alpine:latest
WORKDIR /bin/
COPY --from=builder /bin/app .
EXPOSE 8080
LABEL org.opencontainers.image.source="https://github.com/mohammadne/bookman-auth"
ENTRYPOINT ["/bin/app"]
CMD ["server", "--env=dev"]
like image 311
mohammad Avatar asked Nov 16 '25 16:11

mohammad


1 Answers

IMPORT directive will never be implemented

A long time ago there was proposed IMPORT directive for Docker

Unfortunately, issues are closed while PR's are still open:

  • docker - using shared dockerfile for multiple dockerfiles - Stack Overflow
  • Proposal: Dockerfile add INCLUDE · Issue #735 · moby/moby
  • implement an INCLUDE verb/instruction for docker build files · Issue #974 · moby/moby
  • Add INCLUDE feature · Issue #40165 · moby/moby
  • docker build: initial work on the include command by flavio · Pull Request #2108 · moby/moby
  • Dockerfile templating to automate image creation
  • Templating your Dockerfile like a boss! | by Ahmed ElGamil | Dockbit

Solution for your case

But for your case, all you need - is just a bit of sed

E.g.:

# Case1: inplace templating
EXPOSED_PORT=8081 sed -i "s/EXPOSE 8080/EXPOSE $EXPOSED_PORT/" Dockerfile

# Case2: generating Dockerfile from template
sed "s/EXPOSE 8080/EXPOSE $EXPOSED_PORT/" Dockerfile.template > Dockerfile

Explanation:

  • EXPOSED_PORT=8081 declares local bash variable
  • sed is a tool for text manipulation
  • sed -i "s/EXPOSE 8080/EXPOSE $EXPOSED_PORT/" Dockerfile replaces EXPOSE 8080 to EXPOSE 8081
  • sed "s/EXPOSE 8080/EXPOSE $EXPOSED_PORT/" Dockerfile.template > Dockerfile generates the new Dockerfile from Dockerfile.template
like image 152
Yasen Avatar answered Nov 18 '25 08:11

Yasen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!