Building Container Images
Tips
Review the Dockerfile best practices at https://docs.docker.com/develop/develop-images/dockerfile_best-practices/
RUN commands
Try to bundle multiple RUN commands together to reduce the number of container image layers and their overall size. Concatenating multiple commands with && or ; (with set-x, which stops the script when a non zero exit code is returned).
RUN set -ex; \
yum -y install vim; \
yum clean all
## or,
RUN yum -y install vim && yum clean all
Remember to clean up at the end of each RUN to minimize the layer sizes. Things you can do include:
rm -rf /tmp/* /var/cache/* /var/tmp/*- Clean up package manager caches and remove unnecessary build-only packages
Better yet, use multi-staged builds (https://docs.docker.com/develop/develop-images/multistage-build/) to bundle the results of multiple layers into one.
FROM centos:8 as build
RUN yum -y update
RUN yum -y install vim
FROM centos:8
## We can copy specific artifacts from the build container. Eg:
COPY --from=build /usr/bin/vim /usr/bin/vim
Yum/dnf-based package managers
Yum or dnf package managers are used on Red Hat based distros.
- Install packages with
yum -y installto avoid prompts - At the end of the run,
yum -y clean all, and clean up cachesrm -rf /var/cacheafterwards
Apt-based package managers
Apt-based package managers are used on Ubuntu and Debian based distros.
- Set
DEBIAN_FRONTEND=noninteractiveto prevent some packages from prompting interactive input (tzdatafor example), which leads to indefinite waiting for an user input - At the end of the run,
rm -rf /var/lib/apt/lists/*to clean up.
apk-based package managers
Alpine Linux uses the apk package manager. One neat feature with apk is the ability to group packages into virtual groups which we can uninstall with one command.
- Create virtual groups for build dependencies using
apk add --virtual=build-deps make gcc. These groups can later be removed withapk del --purge build-deps. - At the end of the run,
/var/cache/apk/*to clean up.