Skip to content

Instantly share code, notes, and snippets.

@Jip-Hop
Created March 26, 2023 07:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jip-Hop/09e136e64f8bf342a366cab5d4c08e3b to your computer and use it in GitHub Desktop.
Save Jip-Hop/09e136e64f8bf342a366cab5d4c08e3b to your computer and use it in GitHub Desktop.
Distroless alpine docker image: no shell, no package manager, no busybox. Only the specified packages + dependencies.
FROM alpine as bootstrap
# Optionally add e.g. coreutils (if you don't want to remove the shell)
ARG PACKAGES_TO_INSTALL="openjdk11-jre"
ARG REMOVE_SHELL=1
# Create rootfs folder and enable apk repo
RUN mkdir -p /rootfs/etc/apk && \
cp -a /etc/apk/repositories /rootfs/etc/apk/repositories && \
cp -a /etc/apk/keys /rootfs/etc/apk/keys
# Install the packages we need here,
# this will also install busybox as dependency, which allows all install scripts to run as intended
RUN apk --no-cache -p /rootfs --initdb add alpine-release $PACKAGES_TO_INSTALL
# Then we install dash-binsh, this will purge busybox, as both provide sh
# See p:/bin/sh in the APKINDEX
RUN apk --no-cache -p /rootfs add --no-scripts dash-binsh
# Install findutils in bootstrap stage for symlink cleanup
RUN apk add findutils
# Cleanup the symlinks which point to the removed busybox
# TODO: to also cleanup relative symlinks (don't seem to exist currently),
# I could symlink /rootfs/bin/busybox to /bin/busybox,
# but I'd have to ensure this file is not deleted by find (manually delete afterwards)
RUN find -L /rootfs -samefile /bin/busybox -delete || true
# Option: completely remove the shell
RUN if [[ "$REMOVE_SHELL" == "1" ]]; then \
rm /rootfs/usr/bin/dash /rootfs/bin/sh && \
# Install gawk in bootstrap stage for to cleanup installed packages list
apk add gawk && \
# Remove dash and dash-binsh from list of installed packages:
# - split on empty lines
# - print newline unless it's the first block
# - print each block unless it contains P:dash or P:dash-binsh
# Use $$ in Dockerfile to escape the $
awk -i inplace -v RS="" -v first=1 '{ \
if (!($$0 ~ /^C:(\S*\n)*P:dash(-binsh)?\n/)) { \
if(first==1) { \
first=0; \
} else { \
print ""; \
} \
print $$0; \
} \
}' /rootfs/lib/apk/db/installed; \
fi
# Remove the apk directory
RUN rm -r /rootfs/etc/apk
# Copy the generated rootfs
FROM scratch
ENTRYPOINT ["/usr/bin/java"]
# ENTRYPOINT ["/bin/sh"
COPY --from=bootstrap /rootfs/. /
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment