SlideShare a Scribd company logo
1 of 29
Download to read offline
Improve Your Image Builds
Using BuildKit
Nicholas Dille, Haufe.Group
Docker Captain & Microsoft MVP
@nicholasdille
Nicholas Dille
Husband, father, ops, automator
since 2003
since 2009
since 2010
since 2017
since 2016
Blogger
Speaker
Microsoft MVP
Docker Captain
Haufe.Group
Agenda
BuildKit?
Multi-stage builds
Build cache
Build secrets
SSH
Caching directories
Using BuildKit without Docker
Demo slides
Build engines
Legacy build engine
Default when running docker build
Has been around since the early days
BuildKit powered build engine
Based on
Enabled by environment variable:
Faster and more exible than the legacy build engine
Moby BuildKit
export DOCKER_BUILDKIT=1
Multi Stage Builds
Multiple FROM sections in Dockerfile
Last section represents nal image
Copy les between stages
Build intermediate images using --target name
Prerequisites: Docker 17.09
FROM openjdk:8-jdk AS builder
#...
FROM openjdk:8-jre
COPY --from=builder ...
#...
Multi Stage Builds - Separation
Separate build and runtime environments
Build environment Runtime environment
Compilers (e.g. javac) Runtime (e.g. java)
Build dependencies Execution dependencies
Build tools (e.g. make) -
Large image Smaller attack surface
This also works in the legacy builder
Demo: Multi Stage Builds - Separation
Multi-stage with legacy build system:
Multi-stage with BuildKit:
docker build 
--tag hello-world-java:multi 
.
DOCKER_BUILDKIT=1 docker build 
--tag hello-world-java:multi 
.
build1 build2
final
Built first
Built afterwards
Multi Stage Builds - Concurrency
Stages can be built in parallel when using BuildKit
build1 and build2 are built at the same time
Concurrency is determined based
on the dependency graph
FROM alpine AS build1
RUN touch /opt/binary1
FROM alpine AS build2
RUN touch /opt/binary2
FROM alpine AS final
COPY --from=build1 /opt/binary1 /opt/
COPY --from=build2 /opt/binary2 /opt/
Demo: Multi Stage Builds - Concurrency
Stages have a delay of 10 seconds
Build sequentially using the legacy build engine:
Build in parallel using BuildKit:
Sequential build will take ~20 seconds
Parallel build ~10 seconds
time docker build .
DOCKER_BUILDKIT=1 docker build .
Classic Build Cache Warming
How it works
Builds may not run on the same host
Pull an image to warm the cache
Internal build cache is ignored when using --cache-from
Prerequisites
Added in Docker 1.13
Image must be present locally
docker pull myimage:1
docker build --cache-from myimage:1 --tag myimage:2
Demo: Classic Build Cache Warming
Build and push image:
Reset Docker:
Pull image:
Build with cache from local image:
Internal build cache is used when image does not exist
docker build --tag localhost:5000/hello-world-java .
docker push localhost:5000/hello-world-java
docker system prune --all
docker pull localhost:5000/hello-world-java
docker build --cache-from localhost:5000/hello-world-java .
BuildKit Cache Warming
How it works
Use remote images to warm the cache
Image layers will be downloaded as needed
Same syntax using --cache-from
Prerequisites
Cache information must be embedded during build
Docker 19.03
Demo: BuildKit Cache Warming
Build image with cache information:
Build with remote cache:
export DOCKER_BUILDKIT=1
docker build 
--tag localhost:5000/test:1 
--build-arg BUILDKIT_INLINE_CACHE=1 
.
docker push localhost:5000/test:1
docker system prune --all
docker build 
--cache-from localhost:5000/test:1 
.
Demo: BuildKit Cache Internals
Check manifest for cache information:
curl -s 
-H "Accept: application/vnd.docker.distribution.manifest.v2+j
localhost:5000/v2/test/manifests/1 
| jq --raw-output '.config.digest' 
| while read CONFIG_DIGEST; do 
curl -s 
-H "Accept: application/vnd.docker.container.image.v1
localhost:5000/v2/test/blobs/${CONFIG_DIGEST} 
| jq --raw-output '."moby.buildkit.cache.v0"' 
| base64 -d 
| jq; 
done
Build Secrets
Do not provide secrets using environment variables
ENV burns variables into image
Build arguments (ARG/--build-arg) are only one option
BuildKit to the rescue
Mount using tmpfs
Temporary les in /run/secrets/
Introduced in Docker 18.09
secrets
Demo: Build Secrets
Use experimental syntax in Dockerfile:
Build image with secret from mysite.key:
# syntax=docker/dockerfile:experimental
FROM alpine
RUN --mount=type=secret,id=mysite.key 
ls -l /run/secrets
export DOCKER_BUILDKIT=1
docker build 
--secret id=mysite.key,src=./mysite.key 
--progress plain 
.
SSH Agent Forwarding
Do not copy secrets into image layers
Bad example:
Layers contain SSH key as well as host and user information
BuildKit to the rescue
Forward the socket
Introduced in Docker 18.09
FROM ubuntu
COPY id_rsa /root/.ssh/
RUN scp user@somewhere:/tmp/data .
RUN rm /root/.ssh/id_rsa
SSH agent
Demo: SSH Agent Forwarding
BuildKit forwards the SSH agent socket
Prepare SSH agent:
Forward into build:
Compare local and build:
ssh-keygen -f id_rsa_test -N ''
eval $(ssh-agent -s)
ssh-add id_rsa_test
ssh-add -l
export DOCKER_BUILDKIT=1
docker build --ssh default --progress plain .
ssh-add -l
Demo: SSH Agent Forwarding without BuildKit
Mount existing SSH agent socket
Create environment variable
Prepare SSH agent:
Forward into build:
ssh-keygen -f id_rsa_test
eval $(ssh-agent -s)
ssh-add id_rsa_test
ssh-add -l
docker run -it --rm 
--mount type=bind,src=${SSH_AUTH_SOCK},dst=${SSH_AUTH_SOCK} 
--env SSH_AUTH_SOCK 
alpine-ssh
Persisting Cache Directories
Modern software development relies on countless dependencies
Filling caches takes time
BuildKit to the rescue
can be persisted
Syntax is similar to mounting secrets
Cache directories
# syntax = docker/dockerfile:experimental
FROM ubuntu
RUN --mount=type=cache,target=/tmp/cache 
ls -l /tmp/cache
Demo: Persisting Cache Directories
Enable BuildKit:
Run build:
Run build:
export DOCKER_BUILDKIT=1
docker build 
--progress plain 
--file Dockerfile.cache-warm 
.
docker build 
--progress plain 
--file Dockerfile.cache-check 
.
Using BuildKit
BuildKit can be used in multiple ways
Uses a client/server architecture (daemon and CLI)
Locally Containerized Rootless
Docker X X experimental
Daemon/CLI Demo X X
Daemonless X Demo X
Daemonless is just a wrapper for daemon/CLI
Build container images without access to Docker
Demo: BuildKit locally
Run BuildKit locally
Requires daemon and CLI
Run BuildKit daemon locally:
Run build against daemon:
sudo buildkitd 2>&1 >/tmp/buildkit.log &
buildctl build 
--frontend dockerfile.v0 
--local context=. 
--local dockerfile=.
Demo: BuildKit daemonless containerized
Run a containerized BuildKit daemon on-demand:
docker run -it 
--privileged 
--volume $PWD:/src 
--workdir /src 
--entrypoint buildctl-daemonless.sh 
moby/buildkit build 
--frontend dockerfile.v0 
--local context=. 
--local dockerfile=.
Transition to BuildKit
Sometime it is desirable to change context and Docker le
What you are doing today
How to do this using BuildKit
Remember: Context is the path which is packed and sent to the
daemon
$ docker build 
> --file Dockerfile 
> .
$ buildctl build 
> --frontend dockerfile.v0 
> --local dockerfile=. 
> --local context=.
Transition to BuildKit
Publish an image in a registry
Docker has taught us to build and push container images:
BuildKit can directly upload to an image registry:
Read more about
docker build 
--tag my_image_name 
.
docker push my_image_name
buildctl build 
--frontend dockerfile.v0 
--local dockerfile=. 
--local context=. 
--output type=image,name=my_image_name,push=true
pushing to image registries
Transition to BuildKit
Pass build arguments to customize the image build
The Docker way
The BuildKit way
docker build 
--build-arg name=value 
.
buildctl build 
--frontend dockerfile.v0 
--local dockerfile=. 
--local context=. 
--opt build-arg:name=value
Transition to BuildKit
Use an existing image as build cache
Docker is able to use an local image
BuildKit can use an image in a registry...
...and download helpful layers
docker build 
--cache-from my_image_name 
--tag my_image_name 
.
buildctl build 
--frontend dockerfile.v0 
--local dockerfile=. 
--local context=. 
--output type=image,name=my_image_name,push=true 
--export-cache type=inline 
--import-cache type=registry,ref=my_image_name
Summary
BuildKit brings new features to image building
Multi stage builds
Protect secrets using mounts and SSH forwarding
Improve performance by persisting cache directories
Works with and without Docker
Thanks for joining!
, ,
(see QR code for slides and demos)
(see for slides sources)
Tibor Vass Tonis Tiigi Akihiro Suda
here

More Related Content

What's hot

Understanding the GitOps Workflow and CICD Pipeline - What It Is, Why It Matt...
Understanding the GitOps Workflow and CICD Pipeline - What It Is, Why It Matt...Understanding the GitOps Workflow and CICD Pipeline - What It Is, Why It Matt...
Understanding the GitOps Workflow and CICD Pipeline - What It Is, Why It Matt...
Gibran Badrulzaman
 

What's hot (20)

Git Lab Introduction
Git Lab IntroductionGit Lab Introduction
Git Lab Introduction
 
[KubeConUS2019 Docker, Inc. Booth] Distributed Builds on Kubernetes with Bui...
 [KubeConUS2019 Docker, Inc. Booth] Distributed Builds on Kubernetes with Bui... [KubeConUS2019 Docker, Inc. Booth] Distributed Builds on Kubernetes with Bui...
[KubeConUS2019 Docker, Inc. Booth] Distributed Builds on Kubernetes with Bui...
 
Kubernetes Introduction
Kubernetes IntroductionKubernetes Introduction
Kubernetes Introduction
 
DCEU 18: Dockerfile Best Practices
DCEU 18: Dockerfile Best PracticesDCEU 18: Dockerfile Best Practices
DCEU 18: Dockerfile Best Practices
 
Docker Basics
Docker BasicsDocker Basics
Docker Basics
 
DCSF19 Dockerfile Best Practices
DCSF19 Dockerfile Best PracticesDCSF19 Dockerfile Best Practices
DCSF19 Dockerfile Best Practices
 
Kubernetes security
Kubernetes securityKubernetes security
Kubernetes security
 
Git - An Introduction
Git - An IntroductionGit - An Introduction
Git - An Introduction
 
Docker Registry V2
Docker Registry V2Docker Registry V2
Docker Registry V2
 
Introducing GitLab (September 2018)
Introducing GitLab (September 2018)Introducing GitLab (September 2018)
Introducing GitLab (September 2018)
 
Containers Anywhere with OpenShift by Red Hat
Containers Anywhere with OpenShift by Red HatContainers Anywhere with OpenShift by Red Hat
Containers Anywhere with OpenShift by Red Hat
 
Git 101 for Beginners
Git 101 for Beginners Git 101 for Beginners
Git 101 for Beginners
 
Kubernetes GitOps featuring GitHub, Kustomize and ArgoCD
Kubernetes GitOps featuring GitHub, Kustomize and ArgoCDKubernetes GitOps featuring GitHub, Kustomize and ArgoCD
Kubernetes GitOps featuring GitHub, Kustomize and ArgoCD
 
Jenkins Introduction
Jenkins IntroductionJenkins Introduction
Jenkins Introduction
 
GitOps is the best modern practice for CD with Kubernetes
GitOps is the best modern practice for CD with KubernetesGitOps is the best modern practice for CD with Kubernetes
GitOps is the best modern practice for CD with Kubernetes
 
Build optimization mechanisms in GitLab and Docker
Build optimization mechanisms in GitLab and DockerBuild optimization mechanisms in GitLab and Docker
Build optimization mechanisms in GitLab and Docker
 
Cloud-Native CI/CD on Kubernetes with Tekton Pipelines
Cloud-Native CI/CD on Kubernetes with Tekton PipelinesCloud-Native CI/CD on Kubernetes with Tekton Pipelines
Cloud-Native CI/CD on Kubernetes with Tekton Pipelines
 
FOSDEM 2017: GitLab CI
FOSDEM 2017:  GitLab CIFOSDEM 2017:  GitLab CI
FOSDEM 2017: GitLab CI
 
Understanding the GitOps Workflow and CICD Pipeline - What It Is, Why It Matt...
Understanding the GitOps Workflow and CICD Pipeline - What It Is, Why It Matt...Understanding the GitOps Workflow and CICD Pipeline - What It Is, Why It Matt...
Understanding the GitOps Workflow and CICD Pipeline - What It Is, Why It Matt...
 
Rootless Containers
Rootless ContainersRootless Containers
Rootless Containers
 

Similar to How to Improve Your Image Builds Using Advance Docker Build

Docker & FieldAware
Docker & FieldAwareDocker & FieldAware
Docker & FieldAware
Jakub Jarosz
 

Similar to How to Improve Your Image Builds Using Advance Docker Build (20)

Develop with docker 2014 aug
Develop with docker 2014 augDevelop with docker 2014 aug
Develop with docker 2014 aug
 
Docker Containers: Developer’s experience and building robust developer envir...
Docker Containers: Developer’s experience and building robust developer envir...Docker Containers: Developer’s experience and building robust developer envir...
Docker Containers: Developer’s experience and building robust developer envir...
 
Into to Docker (Central PA Java User Group - 8/14/2017)
Into to Docker (Central PA Java User Group - 8/14/2017)Into to Docker (Central PA Java User Group - 8/14/2017)
Into to Docker (Central PA Java User Group - 8/14/2017)
 
How to _docker
How to _dockerHow to _docker
How to _docker
 
Learning Docker with Thomas
Learning Docker with ThomasLearning Docker with Thomas
Learning Docker with Thomas
 
Docker & FieldAware
Docker & FieldAwareDocker & FieldAware
Docker & FieldAware
 
Deployment Automation with Docker
Deployment Automation with DockerDeployment Automation with Docker
Deployment Automation with Docker
 
Clouds and Tools: Cheat Sheets & Infographics
Clouds and Tools: Cheat Sheets & InfographicsClouds and Tools: Cheat Sheets & Infographics
Clouds and Tools: Cheat Sheets & Infographics
 
Deploying .net core apps to Docker - dotnetConf Local Bengaluru
Deploying .net core apps to Docker - dotnetConf Local BengaluruDeploying .net core apps to Docker - dotnetConf Local Bengaluru
Deploying .net core apps to Docker - dotnetConf Local Bengaluru
 
Java microservicesdockerdockerhubusecase2
Java microservicesdockerdockerhubusecase2Java microservicesdockerdockerhubusecase2
Java microservicesdockerdockerhubusecase2
 
Serverless Container with Source2Image
Serverless Container with Source2ImageServerless Container with Source2Image
Serverless Container with Source2Image
 
Serverless containers … with source-to-image
Serverless containers  … with source-to-imageServerless containers  … with source-to-image
Serverless containers … with source-to-image
 
Docker in Action
Docker in ActionDocker in Action
Docker in Action
 
Learn docker in 90 minutes
Learn docker in 90 minutesLearn docker in 90 minutes
Learn docker in 90 minutes
 
Running Docker in Development & Production (DevSum 2015)
Running Docker in Development & Production (DevSum 2015)Running Docker in Development & Production (DevSum 2015)
Running Docker in Development & Production (DevSum 2015)
 
Docking with Docker
Docking with DockerDocking with Docker
Docking with Docker
 
Academy PRO: Docker. Part 2
Academy PRO: Docker. Part 2Academy PRO: Docker. Part 2
Academy PRO: Docker. Part 2
 
Academy PRO: Docker. Lecture 2
Academy PRO: Docker. Lecture 2Academy PRO: Docker. Lecture 2
Academy PRO: Docker. Lecture 2
 
Continuous Delivery of Cloud Applications with Docker Containers and IBM Bluemix
Continuous Delivery of Cloud Applications with Docker Containers and IBM BluemixContinuous Delivery of Cloud Applications with Docker Containers and IBM Bluemix
Continuous Delivery of Cloud Applications with Docker Containers and IBM Bluemix
 
Tips pour sécuriser ses conteneurs docker/podman
Tips pour sécuriser ses conteneurs docker/podmanTips pour sécuriser ses conteneurs docker/podman
Tips pour sécuriser ses conteneurs docker/podman
 

More from Docker, Inc.

Build & Deploy Multi-Container Applications to AWS
Build & Deploy Multi-Container Applications to AWSBuild & Deploy Multi-Container Applications to AWS
Build & Deploy Multi-Container Applications to AWS
Docker, Inc.
 
Build & Deploy Multi-Container Applications to AWS
Build & Deploy Multi-Container Applications to AWSBuild & Deploy Multi-Container Applications to AWS
Build & Deploy Multi-Container Applications to AWS
Docker, Inc.
 

More from Docker, Inc. (20)

Containerize Your Game Server for the Best Multiplayer Experience
Containerize Your Game Server for the Best Multiplayer Experience Containerize Your Game Server for the Best Multiplayer Experience
Containerize Your Game Server for the Best Multiplayer Experience
 
Build & Deploy Multi-Container Applications to AWS
Build & Deploy Multi-Container Applications to AWSBuild & Deploy Multi-Container Applications to AWS
Build & Deploy Multi-Container Applications to AWS
 
Securing Your Containerized Applications with NGINX
Securing Your Containerized Applications with NGINXSecuring Your Containerized Applications with NGINX
Securing Your Containerized Applications with NGINX
 
How To Build and Run Node Apps with Docker and Compose
How To Build and Run Node Apps with Docker and ComposeHow To Build and Run Node Apps with Docker and Compose
How To Build and Run Node Apps with Docker and Compose
 
Hands-on Helm
Hands-on Helm Hands-on Helm
Hands-on Helm
 
Distributed Deep Learning with Docker at Salesforce
Distributed Deep Learning with Docker at SalesforceDistributed Deep Learning with Docker at Salesforce
Distributed Deep Learning with Docker at Salesforce
 
The First 10M Pulls: Building The Official Curl Image for Docker Hub
The First 10M Pulls: Building The Official Curl Image for Docker HubThe First 10M Pulls: Building The Official Curl Image for Docker Hub
The First 10M Pulls: Building The Official Curl Image for Docker Hub
 
Monitoring in a Microservices World
Monitoring in a Microservices WorldMonitoring in a Microservices World
Monitoring in a Microservices World
 
COVID-19 in Italy: How Docker is Helping the Biggest Italian IT Company Conti...
COVID-19 in Italy: How Docker is Helping the Biggest Italian IT Company Conti...COVID-19 in Italy: How Docker is Helping the Biggest Italian IT Company Conti...
COVID-19 in Italy: How Docker is Helping the Biggest Italian IT Company Conti...
 
Predicting Space Weather with Docker
Predicting Space Weather with DockerPredicting Space Weather with Docker
Predicting Space Weather with Docker
 
Become a Docker Power User With Microsoft Visual Studio Code
Become a Docker Power User With Microsoft Visual Studio CodeBecome a Docker Power User With Microsoft Visual Studio Code
Become a Docker Power User With Microsoft Visual Studio Code
 
How to Use Mirroring and Caching to Optimize your Container Registry
How to Use Mirroring and Caching to Optimize your Container RegistryHow to Use Mirroring and Caching to Optimize your Container Registry
How to Use Mirroring and Caching to Optimize your Container Registry
 
Monolithic to Microservices + Docker = SDLC on Steroids!
Monolithic to Microservices + Docker = SDLC on Steroids!Monolithic to Microservices + Docker = SDLC on Steroids!
Monolithic to Microservices + Docker = SDLC on Steroids!
 
Kubernetes at Datadog Scale
Kubernetes at Datadog ScaleKubernetes at Datadog Scale
Kubernetes at Datadog Scale
 
Labels, Labels, Labels
Labels, Labels, Labels Labels, Labels, Labels
Labels, Labels, Labels
 
Using Docker Hub at Scale to Support Micro Focus' Delivery and Deployment Model
Using Docker Hub at Scale to Support Micro Focus' Delivery and Deployment ModelUsing Docker Hub at Scale to Support Micro Focus' Delivery and Deployment Model
Using Docker Hub at Scale to Support Micro Focus' Delivery and Deployment Model
 
Build & Deploy Multi-Container Applications to AWS
Build & Deploy Multi-Container Applications to AWSBuild & Deploy Multi-Container Applications to AWS
Build & Deploy Multi-Container Applications to AWS
 
From Fortran on the Desktop to Kubernetes in the Cloud: A Windows Migration S...
From Fortran on the Desktop to Kubernetes in the Cloud: A Windows Migration S...From Fortran on the Desktop to Kubernetes in the Cloud: A Windows Migration S...
From Fortran on the Desktop to Kubernetes in the Cloud: A Windows Migration S...
 
Developing with Docker for the Arm Architecture
Developing with Docker for the Arm ArchitectureDeveloping with Docker for the Arm Architecture
Developing with Docker for the Arm Architecture
 
Sharing is Caring: How to Begin Speaking at Conferences
Sharing is Caring: How to Begin Speaking at ConferencesSharing is Caring: How to Begin Speaking at Conferences
Sharing is Caring: How to Begin Speaking at Conferences
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

How to Improve Your Image Builds Using Advance Docker Build

  • 1. Improve Your Image Builds Using BuildKit Nicholas Dille, Haufe.Group Docker Captain & Microsoft MVP @nicholasdille
  • 2. Nicholas Dille Husband, father, ops, automator since 2003 since 2009 since 2010 since 2017 since 2016 Blogger Speaker Microsoft MVP Docker Captain Haufe.Group
  • 3. Agenda BuildKit? Multi-stage builds Build cache Build secrets SSH Caching directories Using BuildKit without Docker Demo slides
  • 4. Build engines Legacy build engine Default when running docker build Has been around since the early days BuildKit powered build engine Based on Enabled by environment variable: Faster and more exible than the legacy build engine Moby BuildKit export DOCKER_BUILDKIT=1
  • 5. Multi Stage Builds Multiple FROM sections in Dockerfile Last section represents nal image Copy les between stages Build intermediate images using --target name Prerequisites: Docker 17.09 FROM openjdk:8-jdk AS builder #... FROM openjdk:8-jre COPY --from=builder ... #...
  • 6. Multi Stage Builds - Separation Separate build and runtime environments Build environment Runtime environment Compilers (e.g. javac) Runtime (e.g. java) Build dependencies Execution dependencies Build tools (e.g. make) - Large image Smaller attack surface This also works in the legacy builder
  • 7. Demo: Multi Stage Builds - Separation Multi-stage with legacy build system: Multi-stage with BuildKit: docker build --tag hello-world-java:multi . DOCKER_BUILDKIT=1 docker build --tag hello-world-java:multi .
  • 8. build1 build2 final Built first Built afterwards Multi Stage Builds - Concurrency Stages can be built in parallel when using BuildKit build1 and build2 are built at the same time Concurrency is determined based on the dependency graph FROM alpine AS build1 RUN touch /opt/binary1 FROM alpine AS build2 RUN touch /opt/binary2 FROM alpine AS final COPY --from=build1 /opt/binary1 /opt/ COPY --from=build2 /opt/binary2 /opt/
  • 9. Demo: Multi Stage Builds - Concurrency Stages have a delay of 10 seconds Build sequentially using the legacy build engine: Build in parallel using BuildKit: Sequential build will take ~20 seconds Parallel build ~10 seconds time docker build . DOCKER_BUILDKIT=1 docker build .
  • 10. Classic Build Cache Warming How it works Builds may not run on the same host Pull an image to warm the cache Internal build cache is ignored when using --cache-from Prerequisites Added in Docker 1.13 Image must be present locally docker pull myimage:1 docker build --cache-from myimage:1 --tag myimage:2
  • 11. Demo: Classic Build Cache Warming Build and push image: Reset Docker: Pull image: Build with cache from local image: Internal build cache is used when image does not exist docker build --tag localhost:5000/hello-world-java . docker push localhost:5000/hello-world-java docker system prune --all docker pull localhost:5000/hello-world-java docker build --cache-from localhost:5000/hello-world-java .
  • 12. BuildKit Cache Warming How it works Use remote images to warm the cache Image layers will be downloaded as needed Same syntax using --cache-from Prerequisites Cache information must be embedded during build Docker 19.03
  • 13. Demo: BuildKit Cache Warming Build image with cache information: Build with remote cache: export DOCKER_BUILDKIT=1 docker build --tag localhost:5000/test:1 --build-arg BUILDKIT_INLINE_CACHE=1 . docker push localhost:5000/test:1 docker system prune --all docker build --cache-from localhost:5000/test:1 .
  • 14. Demo: BuildKit Cache Internals Check manifest for cache information: curl -s -H "Accept: application/vnd.docker.distribution.manifest.v2+j localhost:5000/v2/test/manifests/1 | jq --raw-output '.config.digest' | while read CONFIG_DIGEST; do curl -s -H "Accept: application/vnd.docker.container.image.v1 localhost:5000/v2/test/blobs/${CONFIG_DIGEST} | jq --raw-output '."moby.buildkit.cache.v0"' | base64 -d | jq; done
  • 15. Build Secrets Do not provide secrets using environment variables ENV burns variables into image Build arguments (ARG/--build-arg) are only one option BuildKit to the rescue Mount using tmpfs Temporary les in /run/secrets/ Introduced in Docker 18.09 secrets
  • 16. Demo: Build Secrets Use experimental syntax in Dockerfile: Build image with secret from mysite.key: # syntax=docker/dockerfile:experimental FROM alpine RUN --mount=type=secret,id=mysite.key ls -l /run/secrets export DOCKER_BUILDKIT=1 docker build --secret id=mysite.key,src=./mysite.key --progress plain .
  • 17. SSH Agent Forwarding Do not copy secrets into image layers Bad example: Layers contain SSH key as well as host and user information BuildKit to the rescue Forward the socket Introduced in Docker 18.09 FROM ubuntu COPY id_rsa /root/.ssh/ RUN scp user@somewhere:/tmp/data . RUN rm /root/.ssh/id_rsa SSH agent
  • 18. Demo: SSH Agent Forwarding BuildKit forwards the SSH agent socket Prepare SSH agent: Forward into build: Compare local and build: ssh-keygen -f id_rsa_test -N '' eval $(ssh-agent -s) ssh-add id_rsa_test ssh-add -l export DOCKER_BUILDKIT=1 docker build --ssh default --progress plain . ssh-add -l
  • 19. Demo: SSH Agent Forwarding without BuildKit Mount existing SSH agent socket Create environment variable Prepare SSH agent: Forward into build: ssh-keygen -f id_rsa_test eval $(ssh-agent -s) ssh-add id_rsa_test ssh-add -l docker run -it --rm --mount type=bind,src=${SSH_AUTH_SOCK},dst=${SSH_AUTH_SOCK} --env SSH_AUTH_SOCK alpine-ssh
  • 20. Persisting Cache Directories Modern software development relies on countless dependencies Filling caches takes time BuildKit to the rescue can be persisted Syntax is similar to mounting secrets Cache directories # syntax = docker/dockerfile:experimental FROM ubuntu RUN --mount=type=cache,target=/tmp/cache ls -l /tmp/cache
  • 21. Demo: Persisting Cache Directories Enable BuildKit: Run build: Run build: export DOCKER_BUILDKIT=1 docker build --progress plain --file Dockerfile.cache-warm . docker build --progress plain --file Dockerfile.cache-check .
  • 22. Using BuildKit BuildKit can be used in multiple ways Uses a client/server architecture (daemon and CLI) Locally Containerized Rootless Docker X X experimental Daemon/CLI Demo X X Daemonless X Demo X Daemonless is just a wrapper for daemon/CLI Build container images without access to Docker
  • 23. Demo: BuildKit locally Run BuildKit locally Requires daemon and CLI Run BuildKit daemon locally: Run build against daemon: sudo buildkitd 2>&1 >/tmp/buildkit.log & buildctl build --frontend dockerfile.v0 --local context=. --local dockerfile=.
  • 24. Demo: BuildKit daemonless containerized Run a containerized BuildKit daemon on-demand: docker run -it --privileged --volume $PWD:/src --workdir /src --entrypoint buildctl-daemonless.sh moby/buildkit build --frontend dockerfile.v0 --local context=. --local dockerfile=.
  • 25. Transition to BuildKit Sometime it is desirable to change context and Docker le What you are doing today How to do this using BuildKit Remember: Context is the path which is packed and sent to the daemon $ docker build > --file Dockerfile > . $ buildctl build > --frontend dockerfile.v0 > --local dockerfile=. > --local context=.
  • 26. Transition to BuildKit Publish an image in a registry Docker has taught us to build and push container images: BuildKit can directly upload to an image registry: Read more about docker build --tag my_image_name . docker push my_image_name buildctl build --frontend dockerfile.v0 --local dockerfile=. --local context=. --output type=image,name=my_image_name,push=true pushing to image registries
  • 27. Transition to BuildKit Pass build arguments to customize the image build The Docker way The BuildKit way docker build --build-arg name=value . buildctl build --frontend dockerfile.v0 --local dockerfile=. --local context=. --opt build-arg:name=value
  • 28. Transition to BuildKit Use an existing image as build cache Docker is able to use an local image BuildKit can use an image in a registry... ...and download helpful layers docker build --cache-from my_image_name --tag my_image_name . buildctl build --frontend dockerfile.v0 --local dockerfile=. --local context=. --output type=image,name=my_image_name,push=true --export-cache type=inline --import-cache type=registry,ref=my_image_name
  • 29. Summary BuildKit brings new features to image building Multi stage builds Protect secrets using mounts and SSH forwarding Improve performance by persisting cache directories Works with and without Docker Thanks for joining! , , (see QR code for slides and demos) (see for slides sources) Tibor Vass Tonis Tiigi Akihiro Suda here