Creating more dynamic containers

We can create better containers than just fixing their usage in advance and executing them. Maybe part of the command is the one to keep (like we always want the OpenVPN binary and options to be executed, no matter what), maybe everything needs to be overridden (that's the toolbox container model, such as a /bin/bash command by default, but any other command given in argument can otherwise be executed), or a combination of the two, for a much more dynamic container.

Getting ready

To step through this recipe, you will need a working Docker installation.

How to do it…

To have a fixed command executed by the container, use the ENTRYPOINT instruction. Use an array if the command is followed by arguments to be enforced:

FROM debian:stable-slim
RUN apt-get update -y && 
    apt-get install -y apache2 && 
    rm -rf /var/lib/apt/
EXPOSE 80
ENTRYPOINT ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]

To override the whole command at runtime, use the --entrypoint option:

$ docker run -it --rm --entrypoint /bin/sh httpd
# hostname
585dff032d21

To have a command that can be simply overridden with an argument, use the CMD instruction instead of ENTRYPOINT:

FROM debian:stable-slim
RUN apt-get update -y && 
    apt-get install -y apache2 && 
    rm -rf /var/lib/apt/
EXPOSE 80
CMD ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]

To override the command, simply give another command as an argument at runtime:

$ docker run -it --rm httpd /bin/sh
# hostname
cb1c6a7083ad

We can combine both instructions to have a more dynamic container. In this case, we want to obtain a container always executing /usr/sbin/apache2ctl, and by default starting the daemon in foreground, otherwise overridden by any argument at container launch time:

FROM debian:stable-slim
RUN apt-get update -y && 
    apt-get install -y apache2 && 
    rm -rf /var/lib/apt/
EXPOSE 80
CMD ["-D", "FOREGROUND"]
ENTRYPOINT ["/usr/sbin/apache2ctl"]

If this container is executed as is, nothing changes; apache2ctl gets executed with the -D FOREGROUND option.

However, it becomes a more useful container when giving it arguments, as it dynamically will add them to the apache2ctl command, replacing the original command specified by the CMD instruction:

$ docker run -it --rm httpd -v
Server version: Apache/2.4.10 (Debian)
Server built:   Sep 15 2016 20:44:43

We can interactively pass /usr/sbin/apache2ctl arguments without the need to override the entrypoint, for example, to propose alternatives Apache configuration files or options.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.84.169