SlideShare a Scribd company logo
1 of 37
Download to read offline
bdehamer | CenturyLinkLabs
@bdehamer | @centurylinklabs
Optimizing
Docker Images
Brian DeHamer - CenturyLink Labs
Overview
• Images & Layers
• Minimizing Image Size
• Leveraging the Image Cache
• Dockerfile Tips
• Other Tools
Images & Layers
Interactive Image Creation
• Workflow for creating images by-hand
• docker run -it someimage
• Add/update/delete files
• docker commit
• docker rm
*
Dockerfile
• Automate image creation with docker build
• Place instructions for building image in Dockerfile
• Commands: FROM, COPY, RUN, etc…
• Uses the same run/commit/rm sequence as the
interactive approach
• More repeatable/shareable than the interactive
approach
*
Image Layers
• Each Dockerfile instruction generates a new layer
FROM busybox:latest
MAINTAINER brian
RUN touch foo
CMD ["/bin/sh"]
8c2e06607696
5bd9073989ff
0437ee5cf42c
350e4f999b25
Image Layers
• An image is a hierarchical list of layers
• Each layer has a reference to its parent
• Overall image size is the sum of the sizes of the
individual layers
• Each additional instruction you add to your
Dockerfile will only ever increase the size of your
image
*
Inspecting Layers
• View hierarchy of all local layers
• docker images --tree
• View hierarchy of image layers w/ command
• docker history <TAG>
• View all metadata for a specific layer
• docker inspect <TAG>
• View layer directly on disk
• /var/lib/docker/aufs*
* varies by platform
!"cf2616975b4a Virtual Size: 0 B
!"6ce2e90b0bc7 Virtual Size: 2.433 MB
!"8c2e06607696 Virtual Size: 2.433 MB Tags: busybox:latest
!"d6057c416142 Virtual Size: 2.433 MB
!"70714dda0cf8 Virtual Size: 2.448 MB Tags: foo:latest
$ docker run -it d6057c416142 /bin/sh
Images vs. Layers
• An image is just a tagged hierarchy of layers
• Every layer in an image is runnable
• Helpful when trying to debug Dockerfiles
Minimizing Image Size
$ docker images
REPOSITORY TAG IMAGE ID VIRTUAL SIZE
aa latest 5927ecad7beb 90.22 MB
bb latest 4f02d7398349 100.7 MB
cc latest f466548ecd34 95.47 MB
debian wheezy 1265e16d0c28 84.98 MB
Virtual Image Size
• ~370MB in images?
• Virtual size can be misleading, especially if images
have layers in common
$ docker images --tree
!"511136ea3c5a Virtual Size: 0 B
!"4f903438061c Virtual Size: 84.98 MB
!"1265e16d0c28 Virtual Size: 84.98 MB Tags: debian:wheezy
!"f5f93a9eb89b Virtual Size: 84.98 MB
#"245d46749e30 Virtual Size: 90.22 MB
$ !"5927ecad7beb Virtual Size: 90.22 MB Tags: aa:latest
#"c4a4ebecb14b Virtual Size: 100.7 MB
$ !"4f02d7398349 Virtual Size: 100.7 MB Tags: bb:latest
!"13f53a3a9cb5 Virtual Size: 95.47 MB
!"f466548ecd34 Virtual Size: 95.47 MB Tags: cc:latest
Reuse Your Base Image
• Shared layers are re-used across images
• ~115 MB in images!
Base Images
Image Name Size
fedora:21 241 MB
ubuntu:trusty 188 MB
debian:wheezy 85 MB
alpine:3.1 5 MB
busybox:latest 2 MB
scratch 0 B
Language Images
Image Name Size
ruby:2.2 775 MB
python:3.4 754 MB
perl:5.20 724 MB
node:0.12 706 MB
java:7-jdk 586 MB
golang:1.4 514 MB
Command Chaining
• Beware of creating unnecessary layers with your
Dockerfile commands
FROM debian:wheezy
WORKDIR /tmp
RUN wget -nv http://foo.com/someutil-v1.0.tar.gz
RUN tar -xvf someutil-v1.0.tar.gz
RUN mv /tmp/someutil-v1.0/someutil /usr/bin/someutil
RUN rm -rf /tmp/someutility-v1.0
RUN rm /tmp/someutility-v1.0.tar.gz
Command Chaining
• Chaining commands allows you to clean-up before
the layer is committed
FROM debian:wheezy
WORKDIR /tmp
RUN wget -nv http://foo.com/someutil-v1.0.tar.gz && 
tar -xvf someutil-v1.0.tar.gz && 
mv /tmp/someutil-v1.0/someutil /usr/bin/someutil && 
rm -rf /tmp/someutility-v1.0 && 
rm /tmp/someutility-v1.0.tar.gz
Clean-up After Yourself
• Try to remove any intermediate/temporary files that
you don't need in your final image
FROM debian:wheezy
RUN apt-get update && 
apt-get install -y curl wget git && 
apt-get clean && 
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
Flattening Images
• Can sometimes reduce size by combining layers
• docker export <id> | docker import -
• Lots of other tools and Docker proposals for combining image
layers
• https://github.com/dqminh/docker-flatten
• https://gist.github.com/vieux/6156567
• https://github.com/docker/docker/issues/6906
• Not really recommended
Pack Only What You Need
• Start with FROM scratch and package only the bins/libs you
need for your app
• Use cde to profile your app and identify dependencies
• Statically-linked binaries w/ no dependencies (C, Go, etc…)
• centurylink/golang-builder: helps compile statically-linked Go
apps and package in minimal Docker containers
• centurylink/ca-certs: base image that is just scratch plus the
standard root CA certificates (257 KB)
Leveraging the Image Cache
Image Cache
• All built or pulled layers are saved in the local image
cache
• Docker won’t rebuild an unchanged layer (unless you
force it to)
• Significant increase in build speed when iterating on
Dockerfile
• Cache is invalidated for a layer if either the Dockerfile
instruction or the parent layer is changed
*
Build Context
• The final argument to docker build is typically the
build context
• Allows you to inject local files into your image using
the COPY instruction
• Changes to copied files will also invalidate image
cache
• Dockerfile must be located within the build context
*
Top-to-Bottom
• Place the instructions least likely to change at the top
of your Dockerfile
• Make changes/additions at the bottom
• Place instructions you use across all of your images
(MAINTAINER) at the top so they can be re-used
across all images
.dockerignore
• Place .dockerignore in the root of build context with
list of file/directory patterns to be excluded from build
context
• Very much like .gitignore
• Helpful when copying the entire build context and
want to selectively ignore files
FROM busybox:latest
COPY . /somedir/
*
Beware of Idempotent Operations
• Instructions that may return different results
depending on when they are executed
• apt-get update, git clone, go get, etc…
• Cached layer may not contain what you expect
• Can use --no-cache flag with docker build to
ignore cache
• Use strategic command chaining to bust cache
• Updating branch name does NOT invalidate cache
Bust Cache with Chained Commands
WORKDIR /tmp
RUN git clone https://github.com/bdehamer/sample.git
RUN git checkout v1.0
WORKDIR /tmp
RUN git clone https://github.com/bdehamer/sample.git && 
git checkout v1.0
• Updating branch invalidates cache
Dockerfile Tips
ADD vs. COPY
• ADD & COPY instructions both add files/directories to
the container
• ADD can also handle URLs as a source and will
automatically extract archives
• COPY added in Docker 1.0 and only copies files/dirs
• Use COPY unless there is a specific feature of ADD you
absolutely need
Repeatable Image Builds
• Ideally, anyone should be able to build your
Dockerfile at any time and get the same result
• Vague dependencies can result in unpredictable
builds
RUN apt-get update && apt-get install -y hello
RUN apt-get update && apt-get install -y hello=2.8-4
vs
Shell Variables
• Each Dockerfile instruction is executed in a new
container with a new shell
• Don’t try
RUN export FOO=BAR
RUN cd /tmp
RUN su - someuser
• Instead use
ENV FOO=BAR or RUN FOO=BAR /some/command/that/needs_foo
WORKDIR /tmp
USER someuser
Other Tools / Resources
centurylink/dockerfile-from-image
• Reverse-engineers a Dockerfile from a Docker image
• Can't recreate ADD or COPY commands exactly
$ docker run --rm 
-v /var/run/docker.sock:/var/run/docker.sock 
centurylink/dockerfile-from-image dice
FROM debian:wheezy
MAINTAINER brian@dehamer.com
RUN apt-get update
RUN apt-get install -y rolldice
CMD ["/usr/games/rolldice" "6"]
centurylink/image-graph
• See relationships between layers in your local image
cache
imagelayers.io
• Visualize images on the Docker Hub
• See layers shared between different images
• See the instruction for each layer
• Get information about image size
• Coming soon! Available now!
Additional Reading
• CenturyLink Labs Blog
• http://centurylinklabs.com
• Best Practices for Writing Dockerfiles
• https://docs.docker.com/articles/dockerfile_best-practices
• Squashing Docker Images - Jason Wilder
• http://jasonwilder.com/blog/2014/08/19/squashing-docker-images/
• Create the Smallest Possible Docker Container - Adriaan de Jonge
• http://blog.xebia.com/2014/07/04/create-the-smallest-possible-
docker-container/
bdehamer | CenturyLinkLabs
@bdehamer | @centurylinklabs
Thanks!
Brian DeHamer - CenturyLink Labs

More Related Content

What's hot

An Introduction To Jenkins
An Introduction To JenkinsAn Introduction To Jenkins
An Introduction To JenkinsKnoldus Inc.
 
Docker Swarm 0.2.0
Docker Swarm 0.2.0Docker Swarm 0.2.0
Docker Swarm 0.2.0Docker, Inc.
 
초심자를 위한 도커 소개 및 입문
초심자를 위한 도커 소개 및 입문초심자를 위한 도커 소개 및 입문
초심자를 위한 도커 소개 및 입문Daniel Seo
 
Build, Publish, Deploy and Test Docker images and containers with Jenkins Wor...
Build, Publish, Deploy and Test Docker images and containers with Jenkins Wor...Build, Publish, Deploy and Test Docker images and containers with Jenkins Wor...
Build, Publish, Deploy and Test Docker images and containers with Jenkins Wor...Docker, Inc.
 
Jenkins Pipeline Tutorial | Continuous Delivery Pipeline Using Jenkins | DevO...
Jenkins Pipeline Tutorial | Continuous Delivery Pipeline Using Jenkins | DevO...Jenkins Pipeline Tutorial | Continuous Delivery Pipeline Using Jenkins | DevO...
Jenkins Pipeline Tutorial | Continuous Delivery Pipeline Using Jenkins | DevO...Edureka!
 
Introduction to jenkins
Introduction to jenkinsIntroduction to jenkins
Introduction to jenkinsAbe Diaz
 
[오픈소스컨설팅]Docker기초 실습 교육 20181113_v3
[오픈소스컨설팅]Docker기초 실습 교육 20181113_v3[오픈소스컨설팅]Docker기초 실습 교육 20181113_v3
[오픈소스컨설팅]Docker기초 실습 교육 20181113_v3Ji-Woong Choi
 
Webinar - Unbox GitLab CI/CD
Webinar - Unbox GitLab CI/CD Webinar - Unbox GitLab CI/CD
Webinar - Unbox GitLab CI/CD Annie Huang
 
Kubernetes and container security
Kubernetes and container securityKubernetes and container security
Kubernetes and container securityVolodymyr Shynkar
 
Docker: From Zero to Hero
Docker: From Zero to HeroDocker: From Zero to Hero
Docker: From Zero to Herofazalraja
 
Kubernetes Networking | Kubernetes Services, Pods & Ingress Networks | Kubern...
Kubernetes Networking | Kubernetes Services, Pods & Ingress Networks | Kubern...Kubernetes Networking | Kubernetes Services, Pods & Ingress Networks | Kubern...
Kubernetes Networking | Kubernetes Services, Pods & Ingress Networks | Kubern...Edureka!
 
Docker multi-stage build
Docker multi-stage buildDocker multi-stage build
Docker multi-stage buildAlexei Ledenev
 
Continuous Integration With Jenkins
Continuous Integration With JenkinsContinuous Integration With Jenkins
Continuous Integration With JenkinsEdureka!
 

What's hot (20)

Docker, LinuX Container
Docker, LinuX ContainerDocker, LinuX Container
Docker, LinuX Container
 
An Introduction To Jenkins
An Introduction To JenkinsAn Introduction To Jenkins
An Introduction To Jenkins
 
Docker Swarm 0.2.0
Docker Swarm 0.2.0Docker Swarm 0.2.0
Docker Swarm 0.2.0
 
초심자를 위한 도커 소개 및 입문
초심자를 위한 도커 소개 및 입문초심자를 위한 도커 소개 및 입문
초심자를 위한 도커 소개 및 입문
 
Jenkins presentation
Jenkins presentationJenkins presentation
Jenkins presentation
 
CI/CD with Github Actions
CI/CD with Github ActionsCI/CD with Github Actions
CI/CD with Github Actions
 
Jenkins tutorial
Jenkins tutorialJenkins tutorial
Jenkins tutorial
 
Build, Publish, Deploy and Test Docker images and containers with Jenkins Wor...
Build, Publish, Deploy and Test Docker images and containers with Jenkins Wor...Build, Publish, Deploy and Test Docker images and containers with Jenkins Wor...
Build, Publish, Deploy and Test Docker images and containers with Jenkins Wor...
 
CI/CD with GitHub Actions
CI/CD with GitHub ActionsCI/CD with GitHub Actions
CI/CD with GitHub Actions
 
Jenkins Pipeline Tutorial | Continuous Delivery Pipeline Using Jenkins | DevO...
Jenkins Pipeline Tutorial | Continuous Delivery Pipeline Using Jenkins | DevO...Jenkins Pipeline Tutorial | Continuous Delivery Pipeline Using Jenkins | DevO...
Jenkins Pipeline Tutorial | Continuous Delivery Pipeline Using Jenkins | DevO...
 
Introduction to jenkins
Introduction to jenkinsIntroduction to jenkins
Introduction to jenkins
 
[오픈소스컨설팅]Docker기초 실습 교육 20181113_v3
[오픈소스컨설팅]Docker기초 실습 교육 20181113_v3[오픈소스컨설팅]Docker기초 실습 교육 20181113_v3
[오픈소스컨설팅]Docker기초 실습 교육 20181113_v3
 
Webinar - Unbox GitLab CI/CD
Webinar - Unbox GitLab CI/CD Webinar - Unbox GitLab CI/CD
Webinar - Unbox GitLab CI/CD
 
Kubernetes and container security
Kubernetes and container securityKubernetes and container security
Kubernetes and container security
 
Docker: From Zero to Hero
Docker: From Zero to HeroDocker: From Zero to Hero
Docker: From Zero to Hero
 
Kubernetes Networking | Kubernetes Services, Pods & Ingress Networks | Kubern...
Kubernetes Networking | Kubernetes Services, Pods & Ingress Networks | Kubern...Kubernetes Networking | Kubernetes Services, Pods & Ingress Networks | Kubern...
Kubernetes Networking | Kubernetes Services, Pods & Ingress Networks | Kubern...
 
Gitlab ci-cd
Gitlab ci-cdGitlab ci-cd
Gitlab ci-cd
 
Dockerfile
Dockerfile Dockerfile
Dockerfile
 
Docker multi-stage build
Docker multi-stage buildDocker multi-stage build
Docker multi-stage build
 
Continuous Integration With Jenkins
Continuous Integration With JenkinsContinuous Integration With Jenkins
Continuous Integration With Jenkins
 

Similar to Optimizing Docker Images

Introduction to Docker
Introduction to DockerIntroduction to Docker
Introduction to DockerKuan Yen Heng
 
eZ Publish 5: from zero to automated deployment (and no regressions!) in one ...
eZ Publish 5: from zero to automated deployment (and no regressions!) in one ...eZ Publish 5: from zero to automated deployment (and no regressions!) in one ...
eZ Publish 5: from zero to automated deployment (and no regressions!) in one ...Gaetano Giunta
 
Docker Indy Meetup - An Opinionated View of Building Docker Images and Pipelines
Docker Indy Meetup - An Opinionated View of Building Docker Images and PipelinesDocker Indy Meetup - An Opinionated View of Building Docker Images and Pipelines
Docker Indy Meetup - An Opinionated View of Building Docker Images and PipelinesMatt Bentley
 
Journey to Docker Production: Evolving Your Infrastructure and Processes - Br...
Journey to Docker Production: Evolving Your Infrastructure and Processes - Br...Journey to Docker Production: Evolving Your Infrastructure and Processes - Br...
Journey to Docker Production: Evolving Your Infrastructure and Processes - Br...Docker, Inc.
 
Docker 101 Workshop slides (JavaOne 2017)
Docker 101 Workshop slides (JavaOne 2017)Docker 101 Workshop slides (JavaOne 2017)
Docker 101 Workshop slides (JavaOne 2017)Eric Smalling
 
Getting Started with Docker
Getting Started with DockerGetting Started with Docker
Getting Started with DockerGeeta Vinnakota
 
Preparing your dockerised application for production deployment
Preparing your dockerised application for production deploymentPreparing your dockerised application for production deployment
Preparing your dockerised application for production deploymentDave Ward
 
Webinar: Using Docker Multi-stage Build to Create Advanced Pipelines
Webinar: Using Docker Multi-stage Build to Create Advanced PipelinesWebinar: Using Docker Multi-stage Build to Create Advanced Pipelines
Webinar: Using Docker Multi-stage Build to Create Advanced PipelinesCodefresh
 
Virtualization, Containers, Docker and scalable container management services
Virtualization, Containers, Docker and scalable container management servicesVirtualization, Containers, Docker and scalable container management services
Virtualization, Containers, Docker and scalable container management servicesabhishek chawla
 
Designing True Cross-Platform Apps
Designing True Cross-Platform AppsDesigning True Cross-Platform Apps
Designing True Cross-Platform AppsFITC
 
Build pipelines with bitbucket for Magento
Build pipelines with bitbucket for MagentoBuild pipelines with bitbucket for Magento
Build pipelines with bitbucket for MagentoRrap Software Pvt Ltd
 
Docker for the new Era: Introducing Docker,its components and tools
Docker for the new Era: Introducing Docker,its components and toolsDocker for the new Era: Introducing Docker,its components and tools
Docker for the new Era: Introducing Docker,its components and toolsRamit Surana
 
An introduction to configuring Domino for Docker
An introduction to configuring Domino for DockerAn introduction to configuring Domino for Docker
An introduction to configuring Domino for DockerGabriella Davis
 
DCSF19 Containers for Beginners
DCSF19 Containers for BeginnersDCSF19 Containers for Beginners
DCSF19 Containers for BeginnersDocker, Inc.
 
SenchaCon 2016: Develop, Test & Deploy with Docker - Jonas Schwabe
SenchaCon 2016: Develop, Test & Deploy with Docker - Jonas Schwabe SenchaCon 2016: Develop, Test & Deploy with Docker - Jonas Schwabe
SenchaCon 2016: Develop, Test & Deploy with Docker - Jonas Schwabe Sencha
 
Up and running with docker
Up and running with dockerUp and running with docker
Up and running with dockerMichelle Liu
 
Getting started with Docker
Getting started with DockerGetting started with Docker
Getting started with DockerRavindu Fernando
 
Securing Containers From Day One | null Ahmedabad Meetup
Securing Containers From Day One | null Ahmedabad MeetupSecuring Containers From Day One | null Ahmedabad Meetup
Securing Containers From Day One | null Ahmedabad MeetupKumar Ashwin
 

Similar to Optimizing Docker Images (20)

Introduction to Docker
Introduction to DockerIntroduction to Docker
Introduction to Docker
 
eZ Publish 5: from zero to automated deployment (and no regressions!) in one ...
eZ Publish 5: from zero to automated deployment (and no regressions!) in one ...eZ Publish 5: from zero to automated deployment (and no regressions!) in one ...
eZ Publish 5: from zero to automated deployment (and no regressions!) in one ...
 
Docker Indy Meetup - An Opinionated View of Building Docker Images and Pipelines
Docker Indy Meetup - An Opinionated View of Building Docker Images and PipelinesDocker Indy Meetup - An Opinionated View of Building Docker Images and Pipelines
Docker Indy Meetup - An Opinionated View of Building Docker Images and Pipelines
 
Journey to Docker Production: Evolving Your Infrastructure and Processes - Br...
Journey to Docker Production: Evolving Your Infrastructure and Processes - Br...Journey to Docker Production: Evolving Your Infrastructure and Processes - Br...
Journey to Docker Production: Evolving Your Infrastructure and Processes - Br...
 
Docker 101 Workshop slides (JavaOne 2017)
Docker 101 Workshop slides (JavaOne 2017)Docker 101 Workshop slides (JavaOne 2017)
Docker 101 Workshop slides (JavaOne 2017)
 
Getting Started with Docker
Getting Started with DockerGetting Started with Docker
Getting Started with Docker
 
Docker presentation
Docker presentationDocker presentation
Docker presentation
 
Preparing your dockerised application for production deployment
Preparing your dockerised application for production deploymentPreparing your dockerised application for production deployment
Preparing your dockerised application for production deployment
 
Webinar: Using Docker Multi-stage Build to Create Advanced Pipelines
Webinar: Using Docker Multi-stage Build to Create Advanced PipelinesWebinar: Using Docker Multi-stage Build to Create Advanced Pipelines
Webinar: Using Docker Multi-stage Build to Create Advanced Pipelines
 
Virtualization, Containers, Docker and scalable container management services
Virtualization, Containers, Docker and scalable container management servicesVirtualization, Containers, Docker and scalable container management services
Virtualization, Containers, Docker and scalable container management services
 
Designing True Cross-Platform Apps
Designing True Cross-Platform AppsDesigning True Cross-Platform Apps
Designing True Cross-Platform Apps
 
Build pipelines with bitbucket for Magento
Build pipelines with bitbucket for MagentoBuild pipelines with bitbucket for Magento
Build pipelines with bitbucket for Magento
 
Docker for the new Era: Introducing Docker,its components and tools
Docker for the new Era: Introducing Docker,its components and toolsDocker for the new Era: Introducing Docker,its components and tools
Docker for the new Era: Introducing Docker,its components and tools
 
An introduction to configuring Domino for Docker
An introduction to configuring Domino for DockerAn introduction to configuring Domino for Docker
An introduction to configuring Domino for Docker
 
DCSF19 Containers for Beginners
DCSF19 Containers for BeginnersDCSF19 Containers for Beginners
DCSF19 Containers for Beginners
 
SenchaCon 2016: Develop, Test & Deploy with Docker - Jonas Schwabe
SenchaCon 2016: Develop, Test & Deploy with Docker - Jonas Schwabe SenchaCon 2016: Develop, Test & Deploy with Docker - Jonas Schwabe
SenchaCon 2016: Develop, Test & Deploy with Docker - Jonas Schwabe
 
Up and running with docker
Up and running with dockerUp and running with docker
Up and running with docker
 
Docker tips
Docker tipsDocker tips
Docker tips
 
Getting started with Docker
Getting started with DockerGetting started with Docker
Getting started with Docker
 
Securing Containers From Day One | null Ahmedabad Meetup
Securing Containers From Day One | null Ahmedabad MeetupSecuring Containers From Day One | null Ahmedabad Meetup
Securing Containers From Day One | null Ahmedabad Meetup
 

Recently uploaded

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.pdfsudhanshuwaghmare1
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
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 Processorsdebabhi2
 
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...Martijn de Jong
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 

Recently uploaded (20)

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
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
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
 
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...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Optimizing Docker Images

  • 1. bdehamer | CenturyLinkLabs @bdehamer | @centurylinklabs Optimizing Docker Images Brian DeHamer - CenturyLink Labs
  • 2.
  • 3. Overview • Images & Layers • Minimizing Image Size • Leveraging the Image Cache • Dockerfile Tips • Other Tools
  • 5. Interactive Image Creation • Workflow for creating images by-hand • docker run -it someimage • Add/update/delete files • docker commit • docker rm *
  • 6. Dockerfile • Automate image creation with docker build • Place instructions for building image in Dockerfile • Commands: FROM, COPY, RUN, etc… • Uses the same run/commit/rm sequence as the interactive approach • More repeatable/shareable than the interactive approach *
  • 7. Image Layers • Each Dockerfile instruction generates a new layer FROM busybox:latest MAINTAINER brian RUN touch foo CMD ["/bin/sh"] 8c2e06607696 5bd9073989ff 0437ee5cf42c 350e4f999b25
  • 8. Image Layers • An image is a hierarchical list of layers • Each layer has a reference to its parent • Overall image size is the sum of the sizes of the individual layers • Each additional instruction you add to your Dockerfile will only ever increase the size of your image *
  • 9. Inspecting Layers • View hierarchy of all local layers • docker images --tree • View hierarchy of image layers w/ command • docker history <TAG> • View all metadata for a specific layer • docker inspect <TAG> • View layer directly on disk • /var/lib/docker/aufs* * varies by platform
  • 10. !"cf2616975b4a Virtual Size: 0 B !"6ce2e90b0bc7 Virtual Size: 2.433 MB !"8c2e06607696 Virtual Size: 2.433 MB Tags: busybox:latest !"d6057c416142 Virtual Size: 2.433 MB !"70714dda0cf8 Virtual Size: 2.448 MB Tags: foo:latest $ docker run -it d6057c416142 /bin/sh Images vs. Layers • An image is just a tagged hierarchy of layers • Every layer in an image is runnable • Helpful when trying to debug Dockerfiles
  • 12. $ docker images REPOSITORY TAG IMAGE ID VIRTUAL SIZE aa latest 5927ecad7beb 90.22 MB bb latest 4f02d7398349 100.7 MB cc latest f466548ecd34 95.47 MB debian wheezy 1265e16d0c28 84.98 MB Virtual Image Size • ~370MB in images? • Virtual size can be misleading, especially if images have layers in common
  • 13. $ docker images --tree !"511136ea3c5a Virtual Size: 0 B !"4f903438061c Virtual Size: 84.98 MB !"1265e16d0c28 Virtual Size: 84.98 MB Tags: debian:wheezy !"f5f93a9eb89b Virtual Size: 84.98 MB #"245d46749e30 Virtual Size: 90.22 MB $ !"5927ecad7beb Virtual Size: 90.22 MB Tags: aa:latest #"c4a4ebecb14b Virtual Size: 100.7 MB $ !"4f02d7398349 Virtual Size: 100.7 MB Tags: bb:latest !"13f53a3a9cb5 Virtual Size: 95.47 MB !"f466548ecd34 Virtual Size: 95.47 MB Tags: cc:latest Reuse Your Base Image • Shared layers are re-used across images • ~115 MB in images!
  • 14. Base Images Image Name Size fedora:21 241 MB ubuntu:trusty 188 MB debian:wheezy 85 MB alpine:3.1 5 MB busybox:latest 2 MB scratch 0 B
  • 15. Language Images Image Name Size ruby:2.2 775 MB python:3.4 754 MB perl:5.20 724 MB node:0.12 706 MB java:7-jdk 586 MB golang:1.4 514 MB
  • 16. Command Chaining • Beware of creating unnecessary layers with your Dockerfile commands FROM debian:wheezy WORKDIR /tmp RUN wget -nv http://foo.com/someutil-v1.0.tar.gz RUN tar -xvf someutil-v1.0.tar.gz RUN mv /tmp/someutil-v1.0/someutil /usr/bin/someutil RUN rm -rf /tmp/someutility-v1.0 RUN rm /tmp/someutility-v1.0.tar.gz
  • 17. Command Chaining • Chaining commands allows you to clean-up before the layer is committed FROM debian:wheezy WORKDIR /tmp RUN wget -nv http://foo.com/someutil-v1.0.tar.gz && tar -xvf someutil-v1.0.tar.gz && mv /tmp/someutil-v1.0/someutil /usr/bin/someutil && rm -rf /tmp/someutility-v1.0 && rm /tmp/someutility-v1.0.tar.gz
  • 18. Clean-up After Yourself • Try to remove any intermediate/temporary files that you don't need in your final image FROM debian:wheezy RUN apt-get update && apt-get install -y curl wget git && apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
  • 19. Flattening Images • Can sometimes reduce size by combining layers • docker export <id> | docker import - • Lots of other tools and Docker proposals for combining image layers • https://github.com/dqminh/docker-flatten • https://gist.github.com/vieux/6156567 • https://github.com/docker/docker/issues/6906 • Not really recommended
  • 20. Pack Only What You Need • Start with FROM scratch and package only the bins/libs you need for your app • Use cde to profile your app and identify dependencies • Statically-linked binaries w/ no dependencies (C, Go, etc…) • centurylink/golang-builder: helps compile statically-linked Go apps and package in minimal Docker containers • centurylink/ca-certs: base image that is just scratch plus the standard root CA certificates (257 KB)
  • 22. Image Cache • All built or pulled layers are saved in the local image cache • Docker won’t rebuild an unchanged layer (unless you force it to) • Significant increase in build speed when iterating on Dockerfile • Cache is invalidated for a layer if either the Dockerfile instruction or the parent layer is changed *
  • 23. Build Context • The final argument to docker build is typically the build context • Allows you to inject local files into your image using the COPY instruction • Changes to copied files will also invalidate image cache • Dockerfile must be located within the build context *
  • 24. Top-to-Bottom • Place the instructions least likely to change at the top of your Dockerfile • Make changes/additions at the bottom • Place instructions you use across all of your images (MAINTAINER) at the top so they can be re-used across all images
  • 25. .dockerignore • Place .dockerignore in the root of build context with list of file/directory patterns to be excluded from build context • Very much like .gitignore • Helpful when copying the entire build context and want to selectively ignore files FROM busybox:latest COPY . /somedir/ *
  • 26. Beware of Idempotent Operations • Instructions that may return different results depending on when they are executed • apt-get update, git clone, go get, etc… • Cached layer may not contain what you expect • Can use --no-cache flag with docker build to ignore cache • Use strategic command chaining to bust cache
  • 27. • Updating branch name does NOT invalidate cache Bust Cache with Chained Commands WORKDIR /tmp RUN git clone https://github.com/bdehamer/sample.git RUN git checkout v1.0 WORKDIR /tmp RUN git clone https://github.com/bdehamer/sample.git && git checkout v1.0 • Updating branch invalidates cache
  • 29. ADD vs. COPY • ADD & COPY instructions both add files/directories to the container • ADD can also handle URLs as a source and will automatically extract archives • COPY added in Docker 1.0 and only copies files/dirs • Use COPY unless there is a specific feature of ADD you absolutely need
  • 30. Repeatable Image Builds • Ideally, anyone should be able to build your Dockerfile at any time and get the same result • Vague dependencies can result in unpredictable builds RUN apt-get update && apt-get install -y hello RUN apt-get update && apt-get install -y hello=2.8-4 vs
  • 31. Shell Variables • Each Dockerfile instruction is executed in a new container with a new shell • Don’t try RUN export FOO=BAR RUN cd /tmp RUN su - someuser • Instead use ENV FOO=BAR or RUN FOO=BAR /some/command/that/needs_foo WORKDIR /tmp USER someuser
  • 32. Other Tools / Resources
  • 33. centurylink/dockerfile-from-image • Reverse-engineers a Dockerfile from a Docker image • Can't recreate ADD or COPY commands exactly $ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock centurylink/dockerfile-from-image dice FROM debian:wheezy MAINTAINER brian@dehamer.com RUN apt-get update RUN apt-get install -y rolldice CMD ["/usr/games/rolldice" "6"]
  • 34. centurylink/image-graph • See relationships between layers in your local image cache
  • 35. imagelayers.io • Visualize images on the Docker Hub • See layers shared between different images • See the instruction for each layer • Get information about image size • Coming soon! Available now!
  • 36. Additional Reading • CenturyLink Labs Blog • http://centurylinklabs.com • Best Practices for Writing Dockerfiles • https://docs.docker.com/articles/dockerfile_best-practices • Squashing Docker Images - Jason Wilder • http://jasonwilder.com/blog/2014/08/19/squashing-docker-images/ • Create the Smallest Possible Docker Container - Adriaan de Jonge • http://blog.xebia.com/2014/07/04/create-the-smallest-possible- docker-container/
  • 37. bdehamer | CenturyLinkLabs @bdehamer | @centurylinklabs Thanks! Brian DeHamer - CenturyLink Labs