Skip to content

Instantly share code, notes, and snippets.

@CodyKochmann
Created July 1, 2021 00:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CodyKochmann/c085e60a6c073544dab841c45e99ecaf to your computer and use it in GitHub Desktop.
Save CodyKochmann/c085e60a6c073544dab841c45e99ecaf to your computer and use it in GitHub Desktop.
bash script to flatten docker images down to one layer of files
#!/bin/bash
# by: Marcin Pohl
# created: 2021-06-30
# this bash script js used to flatten and optimize
# docker images for better file access times.
function docker_flatten() {
[[ $# -ne 2 ]] && ( echo "Example usage: docker_flatten python:3.7-slim python:3.7-slim-flat"; exit 255 )
local SRC="$1" # Name or SHA of the source image
local TGT="$2" # Name and optional tag of the target image
ID=$(docker run -d "$SRC" /bin/bash)
### the actual flattening is export + import
docker export "$ID" | docker import - "$TGT"
docker container stop "$ID"
SRC_SIZE=$(docker inspect --format '{{.Size}}' "$SRC")
TGT_SIZE=$(docker inspect --format '{{.Size}}' "$TGT")
echo "" \
| awk -v src="$SRC_SIZE" -v tgt="$TGT_SIZE" \
'{printf "Flattened image is %3.1f%% of the old one.\n", 100*tgt/src}'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment