DEV Community

Francesco Bianco
Francesco Bianco

Posted on • Updated on

Extends ENTRYPOINT or CMD scripts from Dockerfile in a smart way

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"]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Discussion (0)