Reuse Dockerfile snippet

├── commons
│   ├── README.md
│   └── snippet.Dockerfile
├── project1
│   └── Dockerfile
└── project2
    └── Dockerfile

Examined the content of the files

+ cat commons/README.md
This directory contains reusable material for various projects: applications, libraries, etc.



+ cat commons/snippet.Dockerfile
# do something



+ cat project1/Dockerfile
FROM scratch
# do something
include ../commons/snippet.Dockerfile
# do something



+ cat project2/Dockerfile
FROM scratch
# do something
import ../commons/snippet.Dockerfile
# do something

Let’s do some tests

+ docker build project1
Dockerfile:3
--------------------
   1 |     FROM scratch
   2 |     # do something
   3 | >>> include ../commons/snippet.Dockerfile
   4 |     # do something
   5 |     
--------------------
ERROR: failed to solve: dockerfile parse error on line 3: unknown instruction: include

mmmhh…

+ docker build project2
Dockerfile:3
--------------------
   1 |     FROM scratch
   2 |     # do something
   3 | >>> import ../commons/snippet.Dockerfile
   4 |     # do something
   5 |     
--------------------
ERROR: failed to solve: dockerfile parse error on line 3: unknown instruction: import

mmmhhh…

Any suggestions?

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.

Since there was no final answer, could we reopen or reply to the discussion?

All was said by the error message. That is why you didn’t get an answer.

Also note that if you keep sharing code without context and explanation assuming that someone will just understand everything just by looking at your code, you will get no answer next time either.

I have no idea what you were trying to do or why, but there is no import or include in a Dockerfile.

$ cat Dockerfile 
FROM php:latest

# --- COMMON-BEGIN ---
ARG USER=xxx
ARG GROUP=xxx

RUN groupadd \
    "$GROUP" \
&& useradd \
    -m \
    -g "$GROUP" \
    "$USER"
USER "$USER":"$GROUP"
# -- COMMON-END ---

ENTRYPOINT ["php", "--help"]

OK, but I would like to move the central “code chunk” (between COMMON-BEGIN and COMMON-END) to a separate file (e.g. snippet.Dockerfile).
Why?
To be able to reuse/import it in multiple Dockerfiles

So I wonder, can a Dockerfile import a code chunk from another file?

Am I clearer now?

However

I have no idea what you were trying to do or why, but there is no import or include in a Dockerfile.

If that’s the case, I’ll put my mind at peace. That’s exactly what I wanted to know.