Including part of the Dockerfile from somewhere else


I need to create a specific user in 3 different containers. Is it possible to write code responsible for that in a separate file and than include that file in all 3 containers?

You know in the name of the DRY rule :slight_smile:
Or maybe there is a different method to that?

Using FROM mycontainer is doable but I would need to copy and paste quite a lot of dockerfile code from container that already exists in a hub. Would like to avoid that.

A Dockerfile is “just” a text file so you could use your choice of text preprocessor (in this enlightened era it’d be something with lots of curly braces like Jinja; in the past I’ve used tools like m4).

I’m curious what sorts of configuration you’re looking at, though: usually the Dockerfiles I’ve written aren’t much more than RUN apt-get install, a default CMD to launch the service, and maybe a custom entrypoint script to do pre-launch configuration.

Good practice to create your images in a stack–you may be able to try it here. Create your user in one layer and then build “FROM” that layer to create the 3 images. For example, build your 3 images FROM something like this:

# Build from next layer down the stack
FROM alpine:latest

# Create a user and group to launch processes:
# a) in alpine busybox: adduser -D no password, -G group, -h home dir, -s shell;
# b) set permissions on home dir;
# c) add myuser to /etc/sudoers, granting sudo ALL w/ no password  
RUN addgroup myusergroup    && \
    adduser -D -G myusergroup -h /home/myuser -s /bin/ash myuser     && \
    chmod 755 /home/myuser    && \
    echo 'myuser ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers

# Set myuser's home directory as working directory
WORKDIR /home/myuser

# Set myuser to execute all commands below
USER myuser

I would have to create all my containers by without inheriting ( by using from ) from existing container in hub. For example: My container are made using dockerfiles starting from lines:

FROM nginx:
FROM php:
FROM mariadb:

I cannot give them common ancestor container because I would have to pretty much copy&paste Dockerfile contents of the containers listed above.