Extends ENTRYPOINT or CMD scripts from Dockerfile in a smart way

francescobianco profile image Francesco Bianco Updated on ・1 min read

Sometimes we need to create a new image starting from a base image with proper ENTRYPOINT or CMD scripts, eg. docker-entrypoint.sh or service-foreground.sh, it looks in generic Dockerfile as follow

COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
COPY service-foreground.sh /usr/local/bin/service-foreground.sh

ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["service-foreground.sh"]

Now, you require to personalize the behavior of this script just a little bit and you annoyed by recreate these files from zero or copy from the base just to override in your build. Well, think different, you will act an extending approach like class inheritance

## Extend foreground script
RUN cd /usr/local/bin; \
    cp apache2-foreground apache2-foreground-inherit; \
    { \
        echo '#!/bin/bash'; \
        echo '[[ "$1" = "mycmd" ]] && { mycmd "$@"; exit; }'; \
        echo 'apache2-foreground-inherit "$@"'; \
    } > /usr/local/bin/apache2-foreground

## Extend entrypoint script
RUN cd /usr/local/bin; \
    cp docker-entrypoint.sh docker-entrypoint-inherit.sh; \
    { \
        echo '#!/bin/bash'; \
        echo '[[ "$1" = "mycmd" ]] && set -- mycmd "$@"'; \
        echo 'docker-entrypoint-inherit.sh "$@"'; \
    } > /usr/local/bin/docker-entrypoint.sh

Break any rule before writing a new production Dockerfile, be smart and reuse all of things from base image before create new stuff.


Editor guide