Skip to content

Instantly share code, notes, and snippets.

@evadne
Last active July 11, 2023 06:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save evadne/8936c05b1961a4ef1b4e8d86354303d5 to your computer and use it in GitHub Desktop.
Save evadne/8936c05b1961a4ef1b4e8d86354303d5 to your computer and use it in GitHub Desktop.
Build & Cache multi-stage Docker images (with Build Specification for AWS CodeBuild)
# the general idea
ImageTag="git"
FilePath="/Dockerfile"
RepoURI="123456789012.dkr.ecr.eu-west-1.amazonaws.com/repo"
Stages=$(cat $FilePath | grep -oP '^FROM .+ (AS|as) \K(.+)$')
CacheArgs=$(for Stage in $Stages; do echo "--cache-from $RepoURI:cache-$Stage"; done | paste -sd ' ')
BuildArgs="--file $FilePath $CacheArgs"
for Stage in $Stages; do docker pull $RepoURI:cache-$Stage || true; done
for Stage in $Stages; do docker build $BuildArgs --tag $RepoURI:cache-$Stage --target $Stage . || break; done
docker build $BuildArgs --tag $RepoURI:$ImageTag .
docker push $RepoURI:$ImageTag
docker tag $RepoURI:$ImageTag $RepoURI:latest
docker push $RepoURI:latest
for Stage in $Stages; do docker push $RepoURI:cache-$Stage || true; done
version: 0.2
phases:
pre_build:
commands:
- ImageTag=$(echo $CODEBUILD_BUILD_ID | sed 's/[^A-Za-z0-9]/-/g')
- Stages=$(cat $FilePath | grep -oP '^FROM .+ (AS|as) \K(.+)$')
- CacheArgs=$(for Stage in $Stages; do echo "--cache-from $RepoURI:cache-$Stage"; done | paste -sd ' ')
- BuildArgs="--file $FilePath $CacheArgs"
- $(aws ecr get-login --no-include-email)
- for Stage in $Stages; do docker pull $RepoURI:cache-$Stage || true; done
build:
commands:
- for Stage in $Stages; do docker build $BuildArgs --tag $RepoURI:cache-$Stage --target $Stage . || break; done
- docker build $BuildArgs --tag $RepoURI:$ImageTag .
- docker tag $RepoURI:$ImageTag $RepoURI:latest
post_build:
commands:
- |
if [ $CODEBUILD_BUILD_SUCCEEDING = 1 ]; then
docker push $RepoURI:$ImageTag
docker push $RepoURI:latest
for Stage in $Stages; do docker push $RepoURI:cache-$Stage || true; done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment