April 30, 2019

Docker - Optimized Ubuntu based images

Size of Docker images is very important when working in cloud environment and when fast deployment to production is prioritized. Special care needs to be done when creating Dockerfile.
2 min read · 219 words

Official Ubuntu Docker image became very thin, LTS 18.04 version has only 37 MB. Docker images can become huge if we are not careful. Some of best practices for having thin images.

1. Best Practices creating Docker image

1.1. Install only necessary tools

While creating Docker images follow single responsibility principle. Image should run only one task. Some exceptions are allowed for images that are used in infrastructure.

1.2. Clean up after installation

Cleanup unnecessary packages after installation. In Ubuntu, you can remove apt package lists (a few megabytes).

rm -rf /var/lib/apt/lists/*

1.3. Create meaningful layers

Docker creates a new layer for each RUN, COPY, ADD, while it is a bad practice to invoke each copy or command as separate instructions, sometimes is better to create separate layer for specific installation. This way is possible to reuse layers in later builds.

1.4. Add labels

Add labels to all Docker images. You can put any relevant information in labels. This way will be easier in future to identify image. In big environment each product can have multiple images, for different stages, different branches, etc.

2. Dockerfile example

FROM ubuntu:18.04

LABEL maintainer="gregor@plavcak.net"
LABEL net.plavcak.version="1.0.0"
LABEL net.plavcak.repository="https://github.com/plavc/static-site-tools.git"
LABEL net.plavcak.branch="master"

RUN apt-get update && \
    apt-get install hugo -y --no-install-recommends && \
    apt-get install ruby -y --no-install-recommends && \
    rm -rf /var/lib/apt/lists/*

RUN gem install asciidoctor && \
    mkdir /workspace

WORKDIR /workspace