SlideShare a Scribd company logo
Presented By: Yatharth Sharma
How to write a
Dockerfile
Lack of etiquette and manners is a huge turn off.
KnolX Etiquettes
Punctuality
Respect Knolx session timings, you
are requested not to join sessions
after a 5 minutes threshold post
the session start time.
Feedback
Make sure to submit a constructive
feedback for all sessions as it is
very helpful for the presenter.
Silent Mode
Keep your mobile devices in silent
mode, feel free to move out of
session in case you need to attend
an urgent call.
Avoid Disturbance
Avoid unwanted chit chat during
the session.
Our Agenda
01 Why containers?
02 What is a Dockerfile
03 Docker Build Context
04 Dockerfile Format
05 Dockerfile Instructions with Best Practices
06 Docker BuildKit
07 Docker scan
08 Demo
● Dependency issue
Why Containerize?
What problem does containers solve?
Blog: Understanding Containerization and its implementation by Docker
● It is a simple text file with a set of command or instruction. These commands/instructions are executed
successively to perform actions on the base image to create a new docker image.
● Docker can build images automatically by reading the instructions from a Dockerfile.
● Using docker build users can create an automated build that executes several command-line instructions
in succession.
What is a Dockerfile?
Dockerfile
● The docker build command builds an image from a Dockerfile and a context.
● The build context is the set of files at a specified location PATH or URL. The PATH is a directory on your
local filesystem. The URL is a Git repository location.
● Warning: Do not use your root directory, /, as the PATH for your build context, as it causes the build to
transfer the entire contents of your hard drive to the Docker daemon excluding files mentioned in
.dockerignore.
Docker Build Context
Docker Build Context
● Dockerfile format is:
○ # Comment
○ INSTRUCTION arguments
● The instruction is not case-sensitive. However, convention is for them to be UPPERCASE to distinguish
them from arguments more easily.
● A Dockerfile must begin with a FROM instruction.
● FROM may only be preceded by one or more ARG instructions, which declare arguments that are used in
FROM lines in the Dockerfile.
● Instructions:
○ Build Time
○ Run Time
Dockerfile Format
Dockerfile format
● Syntax:
○ FROM [--platform=<platform>] <image>[:<tag>] [AS <name>]
● The FROM instruction initializes a new build stage and sets the Base Image for subsequent instructions.
● ARG is the only instruction that may precede FROM in the Dockerfile.
● FROM can appear multiple times within a single Dockerfile to create multiple images or use one build stage
as a dependency for another.
● Optionally a name can be given to a new build stage by adding AS name to the FROM instruction. The name
can be used in subsequent FROM and COPY --from=<name> instructions to refer to the image built in
this stage.
● The optional --platform flag can be used to specify the platform of the image in case FROM references a
multi-platform image. For example, linux/amd64, linux/arm64, or windows/amd64. By default, the target
platform of the build request is used. Check arch: uname -m || arch || dpkg --print-architecture
Dockerfile Instruction: FROM
FROM
● Syntax:
○ LABEL <key>=<value> <key>=<value> <key>=<value>
● The LABEL instruction adds metadata to an image.
● A LABEL is a key-value pair.
● An image can have more than one label.
● LABEL multi.label1="value1" multi.label2="value2" other="value3"
● LABEL multi.label1="value1" 
multi.label2="value2" 
other="value3"
● Check Labels: docker image inspect <image> | jq '.[].Config.Labels'
Dockerfile Instruction: LABEL
LABEL
● Syntax:
○ EXPOSE <port> [<port>/<protocol>...]
○ EXPOSE 80/tcp
● The EXPOSE instruction informs Docker that the container listens on the specified network ports at runtime.
● You can specify whether the port listens on TCP or UDP, and the default is TCP if the protocol is not specified.
● The EXPOSE instruction does not actually publish the port. It functions as a type of documentation between
the person who builds the image and the person who runs the container, about which ports are intended to
be published.
● To actually publish the port when running the container, use the -p flag on docker run to publish and map
one or more ports, or the -P flag to publish all exposed ports and map them to high-order ports.
● docker run -d -p 80:80/tcp nginx
● docker run -dP nginx
Dockerfile Instruction: EXPOSE
EXPOSE
● Syntax:
○ WORKDIR /path/to/workdir
● The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD
instructions that follow it in the Dockerfile.
● If the WORKDIR doesn’t exist, it will be created even if it’s not used in any subsequent Dockerfile instruction.
● The WORKDIR instruction can resolve environment variables previously set using ENV
● ENV DIRPATH=/path
WORKDIR $DIRPATH
RUN pwd
Dockerfile Instruction: WORKDIR
WORKDIR
● Syntax:
○ ADD [--chown=<user>:<group>] <src>... <dest>
● The ADD instruction copies new files, directories or remote file URLs from <src> and adds them to the
filesystem of the image at the path <dest>.
● Multiple <src> resources may be specified.
● <src> path is always relative to the build context.
Dockerfile Instruction: ADD
ADD
● Syntax:
○ COPY [--chown=<user>:<group>] <src>... <dest>
● The COPY instruction copies new files or directories from <src> and adds them to the filesystem of the
container at the path <dest>
● Multiple <src> resources may be specified.
● <src> path is always relative to the build context.
● Optionally COPY accepts a flag --from=<name> that can be used to set the source location to a previous build
stage (created with FROM .. AS <name>) that will be used instead of a build context sent by the user. In case a
build stage with a specified name can’t be found an image with the same name is attempted to be used
instead.
Dockerfile Instruction: COPY
COPY
● Syntax:
○ USER <user>[:<group>]
○ USER <UID>[:<GID>]
● The USER instruction sets the user name (or UID) and optionally the user group (or GID) to use when running
the image and for any RUN, CMD and ENTRYPOINT instructions that follow it in the Dockerfile.
● Won’t create a user for you
● RUN useradd yatharth
USER yatharth
Dockerfile Instruction: USER
USER
● Syntax:
○ ENV <key>=<value>
● The ENV instruction sets the environment variable <key> to the value <value>.
● ENV MY_NAME="Yatharth Sharma"
● ENV MY_DOG=Snoop Dogg 
MY_OTHER_DOG=Rambo
● ENV MY_CAT fluffy
● You can change the env value using docker run --env <key>=<value>
● If an environment variable is only needed during build, and not in the final image, consider not using ENV
Dockerfile Instruction: ENV
ENV
● Syntax:
○ ARG <name>[=<default value>]
● The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build
command using the --build-arg <varname>=<value> flag.
● If a user specifies a build argument that was not defined in the Dockerfile, the build outputs a warning.
Dockerfile Instruction: ARG
ARG
● Syntax:
○ RUN <command> (shell format)
○ RUN [“executable”, “param1”, “param2”] (exec format)
● The RUN instruction will execute any commands in a new layer on top of the current image and commit the
results.
● Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell
processing does not happen. For example, RUN [ "echo", "$HOME" ] will not do variable substitution on
$HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: RUN
[ "sh", "-c", "echo $HOME" ]
● Example: RUN apt-get dist-upgrade -y
Dockerfile Instruction: RUN
RUN
● Syntax:
○ ENTRYPOINT ["executable", "param1", "param2"]
○ ENTRYPOINT command param1 param2
● An ENTRYPOINT allows you to configure a container that will run as an executable.
● You can override the ENTRYPOINT instruction using the docker run --entrypoint flag.
Dockerfile Instruction: ENTRYPOINT
ENTRYPOINT
● Syntax:
○ CMD command param1 param2 (shell format)
○ CMD ["executable","param1","param2"] (exec format)
○ CMD ["param1","param2"] (default parameter to ENTRYPOINT)
● The main purpose of a CMD is to provide defaults for an executing container.
● There can only be one CMD instruction in a Dockerfile. If you list more than one CMD then only the last CMD
will take effect.
● If you use the shell form of the CMD, then the <command> will execute in /bin/sh -c
Dockerfile Instruction: CMD
CMD
● Both CMD and ENTRYPOINT instructions define what command gets executed when running a container.
There are few rules that describe their co-operation.
○ Dockerfile should specify at least one of CMD or ENTRYPOINT commands.
○ ENTRYPOINT should be defined when using the container as an executable.
○ CMD should be used as a way of defining default arguments for an ENTRYPOINT command or for
executing an ad-hoc command in a container.
○ CMD will be overridden when running the container with alternative arguments.
Dockerfile: ENTRYPOINT && CMD
● Make images as smaller as possible
○ Use distro-less images: Github
○ Use alpine as base-images
○ Use multi-stage builds
● Choosing Correct Build Context
● Using .dockerignore
● Leverage Build Cache
● Dockerfile Instructions sequence and usage best practices.
● Dockerfiles for language specific project - Demo
Dockerfile Best Practices
● Starting with version 18.09, Docker supports a new backend for executing your builds that is provided by
the moby/buildkit project.
● Benefits:
○ Detect and skip executing unused build stages.
○ Parallelize building independent build stages.
○ Incrementally transfer only the changed files in your build context between builds
○ Detect and skip transferring unused files in your build context
● To use the BuildKit backend, you need to set an environment variable DOCKER_BUILDKIT=1
Docker BuildKit
Docker BuildKit
● This feature requires a Docker subscription
● Vulnerability scanning for Docker local images allows developers and development teams to review
the security state of the container images and take actions to fix issues identified during the scan,
resulting in more secure deployments. Docker Scan runs on Snyk engine, providing users with visibility
into the security posture of their local Dockerfiles and local images.
● Sync Docs
● docker scan <image-name:image-tag>
Docker Scan Images
Docker Scan
DEMO
Thank You !
Get in touch with me:
yatharth.sharma@knoldus.com

More Related Content

What's hot (20)

PPTX
Introduction to Docker
Pubudu Jayawardana
 
PPTX
Docker: From Zero to Hero
fazalraja
 
PPTX
Docker introduction
dotCloud
 
PPTX
Why Docker
dotCloud
 
PDF
Introduction to Docker - VIT Campus
Ajeet Singh Raina
 
PDF
Introduction to docker
Instruqt
 
PPTX
What is Docker
Pavel Klimiankou
 
PPT
Docker introduction
Phuc Nguyen
 
PDF
Docker Birthday #3 - Intro to Docker Slides
Docker, Inc.
 
PDF
Introduction to Docker Compose
Ajeet Singh Raina
 
PPTX
Docker 101 - Nov 2016
Docker, Inc.
 
PDF
Docker in real life
Nguyen Van Vuong
 
PDF
Docker 101: Introduction to Docker
Docker, Inc.
 
PPTX
Docker Basics
DuckDuckGo
 
PPTX
Docker 101 : Introduction to Docker and Containers
Yajushi Srivastava
 
PPTX
Docker basics
AmanSoni129
 
PPTX
Dockers and containers basics
Sourabh Saxena
 
PPT
presentation on Docker
Virendra Ruhela
 
PPTX
Docker intro
Oleg Z
 
Introduction to Docker
Pubudu Jayawardana
 
Docker: From Zero to Hero
fazalraja
 
Docker introduction
dotCloud
 
Why Docker
dotCloud
 
Introduction to Docker - VIT Campus
Ajeet Singh Raina
 
Introduction to docker
Instruqt
 
What is Docker
Pavel Klimiankou
 
Docker introduction
Phuc Nguyen
 
Docker Birthday #3 - Intro to Docker Slides
Docker, Inc.
 
Introduction to Docker Compose
Ajeet Singh Raina
 
Docker 101 - Nov 2016
Docker, Inc.
 
Docker in real life
Nguyen Van Vuong
 
Docker 101: Introduction to Docker
Docker, Inc.
 
Docker Basics
DuckDuckGo
 
Docker 101 : Introduction to Docker and Containers
Yajushi Srivastava
 
Docker basics
AmanSoni129
 
Dockers and containers basics
Sourabh Saxena
 
presentation on Docker
Virendra Ruhela
 
Docker intro
Oleg Z
 

Similar to How to write a Dockerfile (20)

PDF
Docker in a JS Developer’s Life
GlobalLogic Ukraine
 
PDF
Docker.pdf
UsamaMushtaq24
 
PPTX
Building Images
Dawood M.S
 
PDF
Computer science docker file Week -6 to7
jemy24r
 
PDF
Docker @ Atlogys
Atlogys Technical Consulting
 
PDF
Introduction of Docker and Docker Compose
Dr. Ketan Parmar
 
PDF
Docker Introduction.pdf
OKLABS
 
PPTX
Powercoders · Docker · Fall 2021.pptx
IgnacioTamayo2
 
PDF
Best Practices for Developing & Deploying Java Applications with Docker
Eric Smalling
 
PDF
Getting Started with Docker
Anup Segu
 
PPTX
Primi passi con Docker - ItalianCoders - 12-01-2021
Alessandro Mignogna
 
PDF
Docker primer and tips
Samuel Chow
 
PPTX
Academy PRO: Docker. Part 2
Binary Studio
 
PDF
docker.pdf
EishaTirRaazia1
 
PDF
Lecture eight to be introduced in class.
nigamsajal14
 
PDF
Docker introduction - Part 1
Alessandro Mignogna
 
PPTX
tips for generating docker containers complaints with the devsecops
Thierry Gayet
 
PDF
Talk about Docker
Meng-Ze Lee
 
PDF
Docker 101
Mirza Nafis Faysal
 
PDF
Build and run applications in a dockerless kubernetes world
Jorge Morales
 
Docker in a JS Developer’s Life
GlobalLogic Ukraine
 
Docker.pdf
UsamaMushtaq24
 
Building Images
Dawood M.S
 
Computer science docker file Week -6 to7
jemy24r
 
Introduction of Docker and Docker Compose
Dr. Ketan Parmar
 
Docker Introduction.pdf
OKLABS
 
Powercoders · Docker · Fall 2021.pptx
IgnacioTamayo2
 
Best Practices for Developing & Deploying Java Applications with Docker
Eric Smalling
 
Getting Started with Docker
Anup Segu
 
Primi passi con Docker - ItalianCoders - 12-01-2021
Alessandro Mignogna
 
Docker primer and tips
Samuel Chow
 
Academy PRO: Docker. Part 2
Binary Studio
 
docker.pdf
EishaTirRaazia1
 
Lecture eight to be introduced in class.
nigamsajal14
 
Docker introduction - Part 1
Alessandro Mignogna
 
tips for generating docker containers complaints with the devsecops
Thierry Gayet
 
Talk about Docker
Meng-Ze Lee
 
Docker 101
Mirza Nafis Faysal
 
Build and run applications in a dockerless kubernetes world
Jorge Morales
 
Ad

More from Knoldus Inc. (20)

PPTX
Angular Hydration Presentation (FrontEnd)
Knoldus Inc.
 
PPTX
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Knoldus Inc.
 
PPTX
Self-Healing Test Automation Framework - Healenium
Knoldus Inc.
 
PPTX
Kanban Metrics Presentation (Project Management)
Knoldus Inc.
 
PPTX
Java 17 features and implementation.pptx
Knoldus Inc.
 
PPTX
Chaos Mesh Introducing Chaos in Kubernetes
Knoldus Inc.
 
PPTX
GraalVM - A Step Ahead of JVM Presentation
Knoldus Inc.
 
PPTX
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
PPTX
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
PPTX
DAPR - Distributed Application Runtime Presentation
Knoldus Inc.
 
PPTX
Introduction to Azure Virtual WAN Presentation
Knoldus Inc.
 
PPTX
Introduction to Argo Rollouts Presentation
Knoldus Inc.
 
PPTX
Intro to Azure Container App Presentation
Knoldus Inc.
 
PPTX
Insights Unveiled Test Reporting and Observability Excellence
Knoldus Inc.
 
PPTX
Introduction to Splunk Presentation (DevOps)
Knoldus Inc.
 
PPTX
Code Camp - Data Profiling and Quality Analysis Framework
Knoldus Inc.
 
PPTX
AWS: Messaging Services in AWS Presentation
Knoldus Inc.
 
PPTX
Amazon Cognito: A Primer on Authentication and Authorization
Knoldus Inc.
 
PPTX
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Knoldus Inc.
 
PPTX
Managing State & HTTP Requests In Ionic.
Knoldus Inc.
 
Angular Hydration Presentation (FrontEnd)
Knoldus Inc.
 
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Knoldus Inc.
 
Self-Healing Test Automation Framework - Healenium
Knoldus Inc.
 
Kanban Metrics Presentation (Project Management)
Knoldus Inc.
 
Java 17 features and implementation.pptx
Knoldus Inc.
 
Chaos Mesh Introducing Chaos in Kubernetes
Knoldus Inc.
 
GraalVM - A Step Ahead of JVM Presentation
Knoldus Inc.
 
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
DAPR - Distributed Application Runtime Presentation
Knoldus Inc.
 
Introduction to Azure Virtual WAN Presentation
Knoldus Inc.
 
Introduction to Argo Rollouts Presentation
Knoldus Inc.
 
Intro to Azure Container App Presentation
Knoldus Inc.
 
Insights Unveiled Test Reporting and Observability Excellence
Knoldus Inc.
 
Introduction to Splunk Presentation (DevOps)
Knoldus Inc.
 
Code Camp - Data Profiling and Quality Analysis Framework
Knoldus Inc.
 
AWS: Messaging Services in AWS Presentation
Knoldus Inc.
 
Amazon Cognito: A Primer on Authentication and Authorization
Knoldus Inc.
 
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Knoldus Inc.
 
Managing State & HTTP Requests In Ionic.
Knoldus Inc.
 
Ad

Recently uploaded (20)

PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 

How to write a Dockerfile

  • 1. Presented By: Yatharth Sharma How to write a Dockerfile
  • 2. Lack of etiquette and manners is a huge turn off. KnolX Etiquettes Punctuality Respect Knolx session timings, you are requested not to join sessions after a 5 minutes threshold post the session start time. Feedback Make sure to submit a constructive feedback for all sessions as it is very helpful for the presenter. Silent Mode Keep your mobile devices in silent mode, feel free to move out of session in case you need to attend an urgent call. Avoid Disturbance Avoid unwanted chit chat during the session.
  • 3. Our Agenda 01 Why containers? 02 What is a Dockerfile 03 Docker Build Context 04 Dockerfile Format 05 Dockerfile Instructions with Best Practices 06 Docker BuildKit 07 Docker scan 08 Demo
  • 4. ● Dependency issue Why Containerize? What problem does containers solve? Blog: Understanding Containerization and its implementation by Docker
  • 5. ● It is a simple text file with a set of command or instruction. These commands/instructions are executed successively to perform actions on the base image to create a new docker image. ● Docker can build images automatically by reading the instructions from a Dockerfile. ● Using docker build users can create an automated build that executes several command-line instructions in succession. What is a Dockerfile? Dockerfile
  • 6. ● The docker build command builds an image from a Dockerfile and a context. ● The build context is the set of files at a specified location PATH or URL. The PATH is a directory on your local filesystem. The URL is a Git repository location. ● Warning: Do not use your root directory, /, as the PATH for your build context, as it causes the build to transfer the entire contents of your hard drive to the Docker daemon excluding files mentioned in .dockerignore. Docker Build Context Docker Build Context
  • 7. ● Dockerfile format is: ○ # Comment ○ INSTRUCTION arguments ● The instruction is not case-sensitive. However, convention is for them to be UPPERCASE to distinguish them from arguments more easily. ● A Dockerfile must begin with a FROM instruction. ● FROM may only be preceded by one or more ARG instructions, which declare arguments that are used in FROM lines in the Dockerfile. ● Instructions: ○ Build Time ○ Run Time Dockerfile Format Dockerfile format
  • 8. ● Syntax: ○ FROM [--platform=<platform>] <image>[:<tag>] [AS <name>] ● The FROM instruction initializes a new build stage and sets the Base Image for subsequent instructions. ● ARG is the only instruction that may precede FROM in the Dockerfile. ● FROM can appear multiple times within a single Dockerfile to create multiple images or use one build stage as a dependency for another. ● Optionally a name can be given to a new build stage by adding AS name to the FROM instruction. The name can be used in subsequent FROM and COPY --from=<name> instructions to refer to the image built in this stage. ● The optional --platform flag can be used to specify the platform of the image in case FROM references a multi-platform image. For example, linux/amd64, linux/arm64, or windows/amd64. By default, the target platform of the build request is used. Check arch: uname -m || arch || dpkg --print-architecture Dockerfile Instruction: FROM FROM
  • 9. ● Syntax: ○ LABEL <key>=<value> <key>=<value> <key>=<value> ● The LABEL instruction adds metadata to an image. ● A LABEL is a key-value pair. ● An image can have more than one label. ● LABEL multi.label1="value1" multi.label2="value2" other="value3" ● LABEL multi.label1="value1" multi.label2="value2" other="value3" ● Check Labels: docker image inspect <image> | jq '.[].Config.Labels' Dockerfile Instruction: LABEL LABEL
  • 10. ● Syntax: ○ EXPOSE <port> [<port>/<protocol>...] ○ EXPOSE 80/tcp ● The EXPOSE instruction informs Docker that the container listens on the specified network ports at runtime. ● You can specify whether the port listens on TCP or UDP, and the default is TCP if the protocol is not specified. ● The EXPOSE instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published. ● To actually publish the port when running the container, use the -p flag on docker run to publish and map one or more ports, or the -P flag to publish all exposed ports and map them to high-order ports. ● docker run -d -p 80:80/tcp nginx ● docker run -dP nginx Dockerfile Instruction: EXPOSE EXPOSE
  • 11. ● Syntax: ○ WORKDIR /path/to/workdir ● The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile. ● If the WORKDIR doesn’t exist, it will be created even if it’s not used in any subsequent Dockerfile instruction. ● The WORKDIR instruction can resolve environment variables previously set using ENV ● ENV DIRPATH=/path WORKDIR $DIRPATH RUN pwd Dockerfile Instruction: WORKDIR WORKDIR
  • 12. ● Syntax: ○ ADD [--chown=<user>:<group>] <src>... <dest> ● The ADD instruction copies new files, directories or remote file URLs from <src> and adds them to the filesystem of the image at the path <dest>. ● Multiple <src> resources may be specified. ● <src> path is always relative to the build context. Dockerfile Instruction: ADD ADD
  • 13. ● Syntax: ○ COPY [--chown=<user>:<group>] <src>... <dest> ● The COPY instruction copies new files or directories from <src> and adds them to the filesystem of the container at the path <dest> ● Multiple <src> resources may be specified. ● <src> path is always relative to the build context. ● Optionally COPY accepts a flag --from=<name> that can be used to set the source location to a previous build stage (created with FROM .. AS <name>) that will be used instead of a build context sent by the user. In case a build stage with a specified name can’t be found an image with the same name is attempted to be used instead. Dockerfile Instruction: COPY COPY
  • 14. ● Syntax: ○ USER <user>[:<group>] ○ USER <UID>[:<GID>] ● The USER instruction sets the user name (or UID) and optionally the user group (or GID) to use when running the image and for any RUN, CMD and ENTRYPOINT instructions that follow it in the Dockerfile. ● Won’t create a user for you ● RUN useradd yatharth USER yatharth Dockerfile Instruction: USER USER
  • 15. ● Syntax: ○ ENV <key>=<value> ● The ENV instruction sets the environment variable <key> to the value <value>. ● ENV MY_NAME="Yatharth Sharma" ● ENV MY_DOG=Snoop Dogg MY_OTHER_DOG=Rambo ● ENV MY_CAT fluffy ● You can change the env value using docker run --env <key>=<value> ● If an environment variable is only needed during build, and not in the final image, consider not using ENV Dockerfile Instruction: ENV ENV
  • 16. ● Syntax: ○ ARG <name>[=<default value>] ● The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag. ● If a user specifies a build argument that was not defined in the Dockerfile, the build outputs a warning. Dockerfile Instruction: ARG ARG
  • 17. ● Syntax: ○ RUN <command> (shell format) ○ RUN [“executable”, “param1”, “param2”] (exec format) ● The RUN instruction will execute any commands in a new layer on top of the current image and commit the results. ● Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, RUN [ "echo", "$HOME" ] will not do variable substitution on $HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: RUN [ "sh", "-c", "echo $HOME" ] ● Example: RUN apt-get dist-upgrade -y Dockerfile Instruction: RUN RUN
  • 18. ● Syntax: ○ ENTRYPOINT ["executable", "param1", "param2"] ○ ENTRYPOINT command param1 param2 ● An ENTRYPOINT allows you to configure a container that will run as an executable. ● You can override the ENTRYPOINT instruction using the docker run --entrypoint flag. Dockerfile Instruction: ENTRYPOINT ENTRYPOINT
  • 19. ● Syntax: ○ CMD command param1 param2 (shell format) ○ CMD ["executable","param1","param2"] (exec format) ○ CMD ["param1","param2"] (default parameter to ENTRYPOINT) ● The main purpose of a CMD is to provide defaults for an executing container. ● There can only be one CMD instruction in a Dockerfile. If you list more than one CMD then only the last CMD will take effect. ● If you use the shell form of the CMD, then the <command> will execute in /bin/sh -c Dockerfile Instruction: CMD CMD
  • 20. ● Both CMD and ENTRYPOINT instructions define what command gets executed when running a container. There are few rules that describe their co-operation. ○ Dockerfile should specify at least one of CMD or ENTRYPOINT commands. ○ ENTRYPOINT should be defined when using the container as an executable. ○ CMD should be used as a way of defining default arguments for an ENTRYPOINT command or for executing an ad-hoc command in a container. ○ CMD will be overridden when running the container with alternative arguments. Dockerfile: ENTRYPOINT && CMD
  • 21. ● Make images as smaller as possible ○ Use distro-less images: Github ○ Use alpine as base-images ○ Use multi-stage builds ● Choosing Correct Build Context ● Using .dockerignore ● Leverage Build Cache ● Dockerfile Instructions sequence and usage best practices. ● Dockerfiles for language specific project - Demo Dockerfile Best Practices
  • 22. ● Starting with version 18.09, Docker supports a new backend for executing your builds that is provided by the moby/buildkit project. ● Benefits: ○ Detect and skip executing unused build stages. ○ Parallelize building independent build stages. ○ Incrementally transfer only the changed files in your build context between builds ○ Detect and skip transferring unused files in your build context ● To use the BuildKit backend, you need to set an environment variable DOCKER_BUILDKIT=1 Docker BuildKit Docker BuildKit
  • 23. ● This feature requires a Docker subscription ● Vulnerability scanning for Docker local images allows developers and development teams to review the security state of the container images and take actions to fix issues identified during the scan, resulting in more secure deployments. Docker Scan runs on Snyk engine, providing users with visibility into the security posture of their local Dockerfiles and local images. ● Sync Docs ● docker scan <image-name:image-tag> Docker Scan Images Docker Scan
  • 24. DEMO
  • 25. Thank You ! Get in touch with me: [email protected]