The Wayback Machine - https://web.archive.org/web/20241013190606/https://www.geeksforgeeks.org/what-is-dockerfile-syntax/
Open In App

What is Dockerfile Syntax?

Last Updated : 08 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Pre-requsites: Docker,Dockerfile

A Dockerfile is a script that uses the Docker platform to generate containers automatically. It is essentially a text document that contains all the instructions that a user may use to create an image from the command line. The Docker platform is a Linux-based platform that allows developers to create and execute containers, self-contained programs, and systems that are independent of the underlying infrastructure. Docker, which is based on the Linux kernel’s resource isolation capabilities, allows developers and system administrators to transfer programs across multiple systems and machines by executing them within containers.

Docker containers may operate on any Linux host thanks to Dockerfiles. Docker images are used to construct container environments for applications, and they may be produced manually or automatically using Dockerfiles. Docker containers can execute Linux and Windows apps. Developers may use Dockerfiles to construct an automated container build that steps through a series of command-line instructions. Docker containerization is essentially virtualization at the operating system level. Without the startup overhead of virtual machines, several independent containers can run within a single Linux instance.

Dockerfiles provide business applications with more flexibility and mobility. Dockerfiles are used by IT companies to bundle programs and their dependencies in a virtual container that may operate on bare metal, in public or private clouds, or on-premises. Numerous apps, worker tasks, and other activities can operate independently on a single physical computer or across multiple virtual machines using containers. Kubernetes is an open-source solution for automating the management and orchestration of Dockerfile-based containerized applications. For a deeper understanding of Dockerfile and how it fits into the overall DevOps workflow, the DevOps Engineering – Planning to Production course offers practical exercises to help you master Dockerfile.

The syntax for writing a Dockerfile and Format

1. FROM

A FROM statement defines which image to download and start from. It must be the first command in your Dockerfile. A Dockerfile can have multiple FROM statements which means the Dockerfile produces more than one image.

Example:

FROM java: 8

2. MAINTAINER

This statement is a kind of documentation, which defines the author who is creating this Dockerfile or who should you contact if it has bugs.

Example:

MAINTAINER Firstname Lastname <example@geeksforgeeks.com>

3. RUN

The RUN statement defines running a command through the shell, waiting for it to finish, and saving the result. It tells what process will be running inside the container at the run time.

Example:

RUN unzip install.zip /opt/install
RUN echo hello

4. ADD

If we define to add some files, ADD statement is used. It basically gives instructions to copy new files, directories, or remote file URLs and then adds them to the filesystem of the image.
To sum up it can add local files, contents of tar archives as well as URLs.

Example:

 Local Files: ADD run.sh /run.sh
Tar Archives: ADD project.tar.gz /install/
URLs: ADD https://project.example-gfg.com/downloads/1.0/testingproject.rpm/test

5. ENV

ENV statement sets the environment variables both during the build and when running the result. It can be used in the Dockerfile and any scripts it calls. It can be used in the Dockerfile as well as any scripts that the Dockerfile calls. These are also persistent with the container and can be referred to at any moment.

Example:

ENV URL_POST=production.example-gfg.com

6. ENTRYPOINT

It specifies the starting of the expression to use when starting your container. Simply ENTRYPOINT specifies the start of the command to run. If your container acts as a command-line program, you can use ENTRYPOINT.

Example:

ENTRYPOINT ["/start.sh"]

7. CMD

CMD specifies the whole command to run. We can say CMD is the default argument passed into the ENTRYPOINT. The main purpose of the CMD command is to launch the software required in a container.

Example:

CMD ["program-foreground"]
CMD ["executable", "program1", "program2"]

Note: If you have both ENVIRONMENT and CMD, they are combined together.

8. EXPOSE

EXPOSE statement maps a port into the container. The ports can be TCP or UDP but by default, it is TCP.

Example:

EXPOSE 3030

9. VOLUME

The VOLUME statement defines shared volumes or ephemeral volumes depending upon whether you have one or two arguments.

Example:

1. If you have two arguments, it maps a host path into a container path.
VOLUME ["/host/path" "/container/path/"]
2. If you have one arguments, it creates a volume that can be inherited by the later containers.
VOLUME ["/shared-data"]

10. WORKDIR

 As the name suggests, WORKDIR sets the directory that the container starts in. Its main purpose is to set the working directory for all future Dockerfile commands.

Example:

WORKDIR /directory-name

11. USER

It sets which user’s container will run as. This can be useful if you have shared network directories involved that assume a fixed username or a fixed user number.

Example:

USER geeksforgeeks
USER 4000

12. ARG 

A variable that can be provided at build time is defined by an ARG Instruction. Once it has been specified in the Dockerfile, you can specify it using the –build-arg switch when creating the image. The Dockerfile supports multiple ARG instructions. The only instruction in the Dockerfile that can come before the FROM instruction is ARG.

After the image is created, ARG values are not accessible. An ARG variable value won’t be accessible to a running container.

Example

ARG image_name=latest
FROM centos:$image_name
docker build -t <image-name>:<tag> --build-arg image_name=centos8 .

Best practices for writing Dockerfiles

  1. As a base image, use official images. And whenever it is possible, use Alpine images as a base image.
  2. Don’t copy unnecessary files and folders or install/use unnecessary packages of software.
  3. Running a container process as root is not recommended. As a non-root user, launch the application container process.
  4. Reduce the number of image layers as much as you can.
  5. Wherever possible, try to use multi-stage Docker files to reduce the size of the image.

Creating a New Dockerfile for Maven

#Using offical maven image as a parent image
FROM maven:3.5-jdk-8-alpine as build

#Setting the working directory to /app
WORKDIR /app

#Copy the current directory contents into the container at current directory
COPY . .

#Install the mvn command for maven
RUN mvn install

By using the above Dockerfile we can build an image of Maven we are setting a Maven alpine image as a base image with the help of FROM command and with the help of WORKDIR setting the working directory for Maven and copy the required files and folders to maven we are using the COPY command and RUN command can download the required commands in the image we are downloading mvn command. 

Note: # is used for comments in Dockerfile.



Previous Article
Next Article

Similar Reads

How To Use Dockerfile Best Practices for Efficient Image Building?
Docker is an open-source platform that enables developers to build, distribute, operate, update, and manage containers. What is Dockerfile?A Dockerfile is just a text file that contains all the commands that must be executed to create a Docker image. The Docker images can then be uploaded to places like DockerHub for either public usage or private
6 min read
What Is Dockerfile Extension ?
Docker is an open-source containerization platform. It helps the developers automate the process-related deployment that enables demand-based scaling, and easy management of applications. Dockerfile enables docker to build images and spin containers from those images. In this article, we'll understand Dockerfile, extensions, syntax, and sample dock
4 min read
How To Clone Private Git Repo With Dockerfile?
Cloning the private git repository in the Dockerfile is often used in situations where you want to build a Docker image of the source code or any assets from the private git repository. Cloning git will reduce the size of the docker image by separating the build environment from the runtime environment using the stage-stage build What is a Dockerfi
5 min read
How To Write Dockerfile For Tomcat?
When you want to dockerize the Java web application by using Tomcat then you must write a Dockerfile for Tomcat. That Dockerfile can be used to build the docker image which consists of its dependencies into a container, ensuring consistency and portability across different environments. What Is Tomcat?Tomcat can also be called Apache Tomcat; the la
5 min read
How To Comment In Dockerfile?
The purpose of comments in a Dockerfile is to both clarify and improve the readability of the instructions. It can also be used to stop execution when testing other code. The comments are meant to serve as a source of code line information. Comments are a frequent way for programmers to document their work. Why are comments used in the Dockerfile?C
3 min read
What is an Multistage Dockerfile?
Docker has revolutionized the world of software development and software deployment by simplifying the process of creating, distributing, and running applications within containers. This feature of Docker is very helpful for developers, so Among Docker's sea of features, multistage Dockerfile stands out as a very powerful tool for optimizing the si
8 min read
Docker Compose vs. Dockerfile with Code Examples
Docker is an open-source platform that empowers developers to automate the deployment of applications inside lightweight, portable containers. Containers encapsulate an application and its conditions, ensuring consistency across various conditions, from advancement to production, the Dockerfile and the Docker Compose file are two essential Docker t
7 min read
What is dockerfile.dev?
In this rapidly developing landscape of software development, it becomes challenging to ensure that the development environment remains consistent at each stage, from local development to testing and production. Docker is a lynchpin among containerization-based platforms bundling applications along with their dependencies. At its core functionality
8 min read
What Is Entrypoint in Dockerfile?
A Dockerfile is a blueprint for building Docker images. It consists of instructions that tell Docker how to build an image. One such instruction is 'ENTRYPOINT'. It specifies the command that will always run when a new container is started. In this article, we will look at the ENTRYPOINT instruction in detail. A Dockerfile is a blueprint for buildi
8 min read
What is Dockerfile?
The operating system (OS) libraries and dependencies required to run the application source code which is not reliant on the underlying operating system (OS) included in the Dockerfile, which is a standardized, executable component. Programmers may design, distribute, launch, run, upgrade, and manage containers using the open-source platform Docker
9 min read
What is Dockerfile.local?
It is essential to create an optimal workflow without interruptions and unnecessary steps for any software project. The concept of uniformity during the application lifecycle has been a primary impulse in the development of modern practices. This article explores how to achieve this by using Docker, particularly focusing on the concept of dockerfil
7 min read
Dockerfile: Output of RUN instruction into a Variable
Docker is an open-source platform that helps a developer to build, test, and deploy applications. It updates and containerizes applications which makes it easier to design an application. With the help of Docker, we can separate the application's infrastructure and the application which allows us easy distribution. Using Docker the developers are a
6 min read
How to Generate a Dockerfile from an Image?
When working with Docker, you may sometimes need to recreate or reverse-engineer a Dockerfile from an existing image. While Docker doesn’t offer a direct method to generate a Dockerfile from an image, you can still extract useful information from the image’s layers and commands. This guide will walk you through the steps to manually recreate a Dock
5 min read
Terraform Syntax With Examples
Managing infrastructure amidst technology's fast-paced evolution has become more complicated. The conventional approach of manual resource provisioning and configuration no longer meets the needs of modern applications and services. As a solution, Infrastructure as Code (IaC) has emerged, allowing organizations to automate infrastructure deployment
3 min read
Docker Prune | Definition,Syntax,Examples
In the evolution of containerization, management of container environments is essential. In this docker prune a command provides a simplified approach of cleaning up unused resources from your containers. The importance of docker prune, and knowing how to improve resource usage by cleaning up the unused storage and enhancing the reliability and eff
13 min read
Complete DevOps Roadmap - Beginner to Advanced
DevOps is considered a set of practices that combines the abilities of Software Development i.e Dev and IT Operations i.e Ops together, which results in delivering top-notch quality software fastly and more efficiently. Its focus is to encourage communication, collaboration, and integration between the software development team and IT operations to
8 min read
Kubernetes Interview Questions and Answers
Kubernetes is a powerful open-source platform for automating deployment, scaling, and operations of application containers across clusters of hosts. It provides a container-centric infrastructure that is efficient, making it a leading choice for managing complex applications. Derived from the Greek word meaning "captain," "helmsman," or "governor,"
15+ min read
DevOps Interview Questions and Answers
DevOps is a set of practices, principles, and tools that combines software development (Dev) and IT operations (Ops). Its primary goal is to shorten the software development lifecycle and deliver high-quality software continuously. DevOps includes collaboration, communication, automation, continuous delivery, and integration between software develo
15+ min read
Top 50+ Docker Interview Questions and Answers (2024)
Docker is an open-source platform designed to automate the deployment, scaling, and management of applications in lightweight containers. Docker is a leading containerization platform that has revolutionized the way applications are developed, shipped, and deployed. Known for its efficiency, scalability, and ease of use, Docker has become an essent
15+ min read
DevOps Tutorial
DevOps is a collection of two words, "Development" and "Operations," representing a cultural approach that emphasizes collaboration between development and operations teams to streamline the entire software delivery lifecycle. This DevOps tutorial is designed to help learn DevOps basics and advanced concepts, including Git, Ansible, Docker, Puppet,
9 min read
Docker Tutorial
In this Docker Tutorial, you’ll learn all the basic to advanced concepts like Docker installation, Docker container, Docker commands, Docker run, Docker images, Docker compose, Docker engine, Docker networking, etc. Docker is a powerful tool used for developing, packaging, and deploying applications efficiently. Docker is a container management ser
8 min read
Kubernetes Tutorial
In this Kubernetes Tutorial you’ll learn all the basics to advanced concepts like Kubernetes service , Kubernetes cluster construction , Kubernetes deployment , Kubernetes Architecture , etc. This free tutorial on Kubernetes will provide all the essential information needed to understand and work with Kubernetes, including the use of APIs, installa
7 min read
Amazon Web Services (AWS) Tutorial
This AWS tutorial, or Amazon Web Service tutorial, is designed for beginners and professionals to learn AWS's basic and advanced concepts . Learn about the various topics of AWS such as introduction, history of AWS, global infrastructure, features of AWS, IAM, storage services, database services, application Services, etc., and other AWS products s
8 min read
Microsoft Azure Tutorial
Designed by Microsoft in 2010, Microsoft Azure is one of the widely used cloud computing platforms. Azure provides a wide variety of services, such as cloud storage, compute services, network services, cognitive services, databases, analytics, and IoT. It makes building, deploying, and managing applications very easy. All the Microsoft Azure fundam
13 min read
Docker Commands
Docker is an open-source project that automates the deployment of applications as movable, independent containers that can run locally or in the cloud. You can divide your applications from your infrastructure with the help of Docker, allowing for quick software delivery and it also allows you to manage your infrastructure in the same ways that you
7 min read
What is CI/CD?
CI And CD is the practice of automating the integration of code changes from multiple developers into a single codebase. It is a software development practice where the developers commit their work frequently to the central code repository (Github or Stash). Then there are automated tools that build the newly committed code and do a code review, et
6 min read
Docker - COPY Instruction
In Docker, there are two ways to copy a file, namely, ADD and COPY. Though there is a slight difference between them in regard to the scope of the functions, they more or less perform the same task. In this article, we will primarily focus on the COPY instruction of Docker. If you want to copy files and directories inside a Docker Container from yo
2 min read
How to Run a Python Script using Docker?
Docker helps you to run your python application very smoothly in different environments with out worrying about underlying platforms. Once you build an image using dockerfile you can run that image where ever you want to run. Docker image will help you to package all the dependencies required for the application which will used for further while ru
7 min read
What is Docker?
Docker is a set of Platforms as a service (PaaS) products that use Operating system-level virtualization to deliver software in packages called containers. Containers are isolated from one another and bundle their own software, libraries, and configuration files; they can communicate with each other through well-defined channels. All containers are
15+ min read
Introduction to Kubernetes (K8S)
Kubernetes is an open-source platform that manages Docker containers in the form of a cluster. Along with the automated deployment and scaling of containers, it provides healing by automatically restarting failed containers and rescheduling them when their hosts die. This capability improves the application’s availability. What is Kubernetes (k8s)?
12 min read