docker optimization best practice linter - ghdrako/doc_snipets GitHub Wiki

scoop install hadolint

Flattening Docker images

To flatten a Docker image, follow these series of steps:

  1. Run a Docker container with the usual image.
  2. Do a docker export of the running container to a .tar file.
  3. Do a docker import of the .tar file into another image.
$ docker history <your_dockerhub_user>/nginx-hello-world:latest
#  run a Docker image with the latest image
$ docker run -d --name nginx \
<your_dockerhub_user>/nginx-hello-world:latest
# export
$ docker export nginx > nginx-hello-world-flat.tar
# import
cat nginx-hello-world-flat.tar | docker import - \
<your_dockerhub_user>/nginx-hello-world:flat
docker history <your_dockerhub_user>/nginx-hello-world:flat

Optimizing containers with distroless images

Distroless images are the most minimal of images and only contain your application, dependencies, and the necessary files for your container process to run. Most of the time, you do not need package managers such as apt or even a shell such as bash. Not having a shell has its advantages. For one, it will help you avoid any outside party gaining access to your container while it is running. Your container now has a small attack surface, which means it won't have many security vulnerabilities. Google provides distroless images in their official GCR registry, which is available on their GitHub page at https://github.com/GoogleContainerTools/distroless.

FROM golang:1.12.4 AS build
WORKDIR /tmp
COPY app.go .
RUN GOOS=linux go build -a -installsuffix cgo -o app . && chmod
+x ./app
FROM gcr.io/distroless/base
WORKDIR /tmp
COPY --from=build /tmp/app .
CMD ["./app"]

gcr.io/distroless/base as the base image contains a minimalistic Linux glibc-enabled system and lacks a package manager or a shell. You can use it to run binaries compiled in a language such as Go, Rust, or D.

$ docker build -t <your_dockerhub_user>/\
go-hello-world:distroless .
$ docker run <your_dockerhub_user>/go-hello-world:distroless
$ docker images

there are distroless images available for interpreted programming languages such as Python and Java, so you can use them instead of the bloated image containing the toolkits.