Last active
July 11, 2023 06:33
-
-
Save evadne/8936c05b1961a4ef1b4e8d86354303d5 to your computer and use it in GitHub Desktop.
Build & Cache multi-stage Docker images (with Build Specification for AWS CodeBuild)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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