1. Home
Docker

Understanding Docker: A Comprehensive Overview

Discover comprehensive Docker tutorials designed for all skill levels. Learn containerization, deployment, and best practices to enhance your development workflow.

  • 11
  • 4
right-top-arrow
4

What is a Dockerfile? Explained with Examples

Updated on 29/08/2024484 Views

Introduction

A Dockerfile is a script containing instructions on how to build a Docker image.

the code, runtime, libraries, environment variables, and configuration files. Dockerfiles are the cornerstone of Docker's containerization technology, enabling developers to automate the deployment of applications inside containers.

Overview

Before delving into what a Dockerfiles is, it is essential to understand Docker and the concept of containers. Docker is a platform that utilizes OS-level virtualization to deliver software in packages called containers.

Dockerfile containers are isolated from one another and bundle their software, libraries, and configuration files. They can communicate through well-defined channels. A single-kernel operating system runs all containers and uses fewer resources than virtual machines. In this tutorial, we will explore what a Dockerfile is, Dockerfile documentation, commands, examples, and more.

Purpose of a Dockerfile

A Dockerfile automates the process of creating Docker images. Instead of manually performing the steps to set up an environment and install software, a Dockerfile provides a simple and repeatable way to do so. This automation ensures consistency across different environments, making developing, testing, and deploying applications easier.

The Basic Structure of a Dockerfile

A Dockerfile command consists of instructions, each specifying a step to perform in the image-building process. Here is a look at the Dockerfile format in brief:

  • FROM: It Specifies the base image to use for the Docker image. This is often an official image from Docker Hub.
  • ENV: Sets environment variables. In this example, it sets DEBIAN_FRONTEND to noninteractive to avoid prompts during package installations.
  • COPY: Copies files or manuals from the host machine into the Docker image.
  • RUN: Executes commands in the container during the image build process. Commonly used to install packages or run scripts.
  • WORKDIR: Sets the functional directory for the subsequent instructions.
  • CMD: It specifies the default command to run when the container starts. Unlike RUN, this command runs when the container is instantiated.

Detailed Dockerfile Instructions

Here, we will explore the detailed Dockerfile documentation, covering all its instructions, best practices, and some advanced features.

Overview of Dockerfile Instructions

1. FROM

It sets the base image for the Docker image being built. This is typically the first instruction in every Dockerfile.

Syntax:

FROM <image>[:<tag>]

Example:

FROM ubuntu:20.04

2. LABEL

The LABEL instruction adds metadata to an image. Labels are key-value pairs that provide useful information about the image.

Syntax:

LABEL <key>=<value> ...

Example:

LABEL maintainer="maintainer@example.com"

LABEL version= "1.0"

LABEL description= "A sample Dockerfile"

3. ENV

The ENV instruction sets environment variables, which can be used within the Dockerfile and by applications running in the container.

Syntax:

ENV <key>=<value> ...

Example:

ENV DEBIAN_FRONTEND=noninteractive

4. RUN

The Dockerfile RUN command executes in a new layer on top of the current image and commits the results. It is used to install packages and do other setup tasks.

Syntax:

RUN <command>

Example:

RUN apt-get update && apt-get install -y curl

5. COPY

The COPY instruction copies files or directories from the host machine into the Docker image. It only supports local files and directories as the source.

Syntax:

COPY <src><dest>

Example:

COPY . /app

6. ADD

The ADD instruction is similar to COPY but with additional capabilities. It can copy files from URLs and automatically handle tarball extraction.

Syntax:

ADD <src><dest>

Example:

ADD https://example.com/file.tar.gz /app/

7. WORKDIR

The WORKDIR sets the working directory for any subsequent instructions in the Dockerfile.

Syntax:

WORKDIR <path>

Example:

WORKDIR /app

8. CMD

The CMD instruction specifies the default command to run when a container is started. It can be countermanded by passing a command to Docker run.

Syntax:

CMD ["executable", "param1", "param2"]

Example:

CMD ["python", "app.py"]

9. ENTRYPOINT

The ENTRYPOINT instruction configures a container to run as an executable. It sets a default command but allows arguments to be passed when starting the container.

Syntax:

ENTRYPOINT ["executable", "param1", "param2"]

Example:

ENTRYPOINT ["python"]

CMD ["app.py"]

10. EXPOSE

The EXPOSE instruction reports Docker that the container listens on the selected network ports at runtime. This is mainly for documentation and does not publish the port.

Syntax:

EXPOSE <port> [<port>/<protocol>...]

Example:

EXPOSE 8080

11. VOLUME

The VOLUME instruction creates a mount point with the specified path and marks it as holding externally mounted volumes from the host or other containers.

Syntax:

VOLUME ["<path>"]

Example:

VOLUME ["/data"]

12. USER

This instruction creates the user name or UID to utilize for running the image and for subsequent instructions.

Syntax:

USER <username>[:<group>]

Example:

USER appuser

13. ARG

The ARG instruction defines a variable that users can pass at build-time to the builder with the Docker build command. These variables do not persist in the intermediate or final images.

Syntax:

ARG <name>[=<default value>]

Example:

ARG VERSION=1.0

How to Download Dockerfiles from a Dockerfile Registry?

Dockerfiles can often be found in public repositories like GitHub, Docker Hub, or specialized Dockerfile registries. Here is how to download Dockerfiles:

From GitHub:

  1. Navigate to the repository containing the Dockerfile.
  2. Locate the Dockerfile in the project directory.
  3. Click on the Dockerfile to open it.
  4. Click the "Raw" button to view the plain text version.
  5. Right-click and choose "Save As..." to download on your local machine.

From Docker Hub:

  1. Go to Docker Hub.
  2. Search for the desired image.
  3. Click on the image name to open its details page.
  4. Look for the "Dockerfile" tab or link which often provides the Dockerfile used to build the image.
  5. Copy the contents and save it as a Dockerfile on your local machine.

Creating a Dockerfile from Scratch

Here are the steps to create a basic Dockerfile:

  1. Open a Text Editor:

You can make use of a text editor like VS Code, Sublime Text, or even Notepad.

Start with a Base Image:

FROM ubuntu:20.04

  1. Set Maintainer Information (optional but recommended):

LABEL maintainer="yourname@example.com"

  1. Install Dependencies:

RUN apt-get update && apt-get install -y \

python3 \

python3-pip

  1. Copy Files to the Image:

COPY . /app

  1. Set the Working Directory:

WORKDIR /app

  1. Specify the Command to Run the Application:

CMD ["python3", "app.py"]

  1. Save the File:

Save this file with the name Dockerfile (no file extension).

Example Dockerfile for a Node.js Application

Let's create a more comprehensive dockerfile example for a Node.js application:

# Use the official Node.js image as the base image

FROM node:14

# Create and change to the app directory

WORKDIR /usr/src/app

# Copy the package.json and package-lock.json files

COPY package*.json ./

# Install dependencies

RUN npm install

# Copy the rest of the application code

COPY . .

# Expose the application port

EXPOSE 8080

# Define the command to run the application

CMD ["node", "server.js"]

In this Dockerfile:

  • We use the official Node.js image as the base.
  • Set the directory to /usr/src/app.
  • Copy the package.json files to the working directory.
  • Run npm install to install dependencies.
  • Copy the rest of the application code.
  • Expose port 8080.
  • Define the default command to start the application.

Building Dockerfile: Building and Running a Docker Image

To establish a Docker image from a Dockerfile, navigate to the directory including the Dockerfile and run:

docker build -t my-node-app.

This command instructs Docker to create an image with the tag my-node-app using the current directory (denoted by .) as the build context.

To run a container from the image:

docker run -p 8080:8080 my-node-app

This command runs a container from the my-node-app image and maps port 8080 of the container to port 8080 on the host.

Advanced Dockerfile Features

Advanced features of Dockerfile are explained below with examples.

Multi-Stage Builds

Multi-stage builds help reduce the size of the final image by allowing you to copy only the necessary artifacts from one stage to another.

Example:

# Stage 1: Build the application

FROM node:14 as build

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

RUN npm run build

# Stage 2: Create the final image

FROM nginx:alpine

COPY --from=build /usr/src/app/build /usr/share/nginx/html

Build Arguments

Build arguments allow you to pass variables at build-time, which can be used in the Dockerfile.

Example:

ARG NODE_VERSION=14

FROM node:${NODE_VERSION}

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

CMD ["node", "server.js"]

Build with:

docker build --build-arg NODE_VERSION=16 -t my-node-app .

Best Practices for Writing Dockerfiles

What is Dockerfile used for? Find here the best practices for running Dockerfile on windows:

  • Reduce the Number of Layers: Each RUN, COPY, and ADD instruction adds a layer to the image. Use multi-line commands to reduce the number of layers.
  • Leverage Caching: Docker caches the results of each instruction. To take advantage of caching, order instructions from least to most frequently changing.
  • Use .dockerignore: Similar to .gitignore, a .dockerignore file eliminated files and directories from the build context to reduce image size and build time.
  • Use Official Base Images: Start with official base images when possible, as they are maintained and optimized by the community.
  • Avoid Hard-Coding Secrets: Do not hard-code secrets or sensitive information in the Dockerfile. Use build-time and runtime variables or Docker secrets for secure management.

Final Thoughts

Dockerfile is a powerful tool for automating the creation of Docker images, enabling consistent and portable environments for application deployment. By understanding what a Dockerfile is, developers can efficiently create and manage containerized applications. Whether you are building simple applications or complex multi-service systems, Dockerfiles provide a robust framework for containerization.

FAQs

1. What is the Dockerfile?

A Dockerfile is a script containing instructions for building a Docker image. It specifies the base image, dependencies, configurations, and the commands to run within the container.

2. What is my Dockerfile?

"My Dockerfile" refers to the specific Dockerfile you create to define the environment and setup for your application or service, tailored to your project's needs.

3. What is the difference between Docker and Dockerfile?

Docker platform that automates the deployment of applications in lightweight containers. A Dockerfile is a text file which includes instructions for creating a Docker image, which Docker uses to create containers.

4. How is Dockerfile called?

A Dockerfile is used by invoking the 'docker build' command in the terminal, which reads the Dockerfile to build a Docker image.

5. What do I write in Dockerfile?

In a Dockerfile, you write instructions like FROM, RUN, COPY, WORKDIR, CMD, and others to set up the base image, install dependencies, copy files, and define the command to run your application.

6. What is the benefit of Dockerfile?

Dockerfiles provide a reproducible and automated way to build Docker images, ensuring consistent environments across different stages of development, testing, and production.

7. Do you need Dockerfile?

Yes, if you want to automate the creation of Docker images for your applications. It simplifies your containerized environments' setup, deployment, and version control.

8. Who should write the Dockerfile?

Developers or DevOps engineers typically write Dockerfiles to define the environment, dependencies, and setup needed for their applications to run in Docker containers.

9. What is entrypoint in Dockerfile?

The ENTRYPOINT instruction in a Dockerfile specifies a command that will always run when the container starts. It allows the container to be run as if it were an executable.

Kechit Goyal

Kechit Goyal

Team Player and a Leader with a demonstrated history of working in startups. Strong engineering professional with a Bachelor of Technology (BTech…Read More

Talk to Career Expert
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...