Dockerfile Syntax: A Complete Beginner’s Guide To Success

Docker syntax

Table of Contents

Get up to 50% off now

Become a partner with CyberPanel and gain access to an incredible offer of up to 50% off on CyberPanel add-ons. Plus, as a partner, you’ll also benefit from comprehensive marketing support and a whole lot more. Join us on this journey today!

A Dockerfile is an incredibly simple text file that contains a set of instructions for building a Docker image. Each of these instructions define a step of the process of image creation. These processes can include setting the base image, installing packages, copying files, and configuring commands. 

In this guide, we shall master the Dockerfile syntax for maximum automation. 

Basic Structure of a Dockerfile

A typical Dockerfile follows a structured, top-down approach. Here’s a basic example and its flow:

FROM node:18-alpine

WORKDIR /app

COPY package.json ./

Tech Delivered to Your Inbox!

Get exclusive access to all things tech-savvy, and be the first to receive 

the latest updates directly in your inbox.

RUN npm install

COPY . .

EXPOSE 3000

CMD [“node”, “server.js”]

Explanation of Flow:

  • FROM: Sets the base image.
  • WORKDIR: Defines the working directory.
  • COPY: Moves necessary files into the image.
  • RUN: Executes a build step (e.g., installing dependencies).
  • EXPOSE: Declares which port the container will listen on.
  • CMD: Specifies the default command to run when the container starts.

Key Dockerfile Instructions – Cheat Sheet & Description 

INSTRUCTIONPURPOSE
FROMSets the base image for the container (must be the first instruction).
RUNExecutes a command during image build (e.g., installing packages).
CMDProvides default arguments for the container at runtime.
LABELAdds metadata to the image (e.g., version, maintainer info).
EXPOSEInforms Docker that the container listens on specified ports.
ENVSets environment variables inside the container.
ADD vs COPYBoth copy files into the container, but ADD can also extract archives and download URLs. COPY is simpler and preferred for just copying files.
ENTRYPOINTConfigures a container to run as an executable with fixed command.
VOLUMECreates a mount point for external storage (persistent data).
WORKDIRSets the working directory for RUN, CMD, ENTRYPOINT, etc.
ARGDefines a build-time variable (only available during docker build).
USERSpecifies the user under which the container will run.
HEALTHCHECKDefines how Docker should test the container to check if it’s still working.
ONBUILDAdds instructions that will execute when the image is used as a base for another build.
  1. FROM

FROM specifies the base image while building a new Docker image, each Dockerfile must begin from here. 

Syntax:

FROM ubuntu:20.04

  1. RUN

RUN executes all the commands in a new layer that is placed on top of the current images and commits the results. 

Syntax:

Enhance Your CyerPanel Experience Today!
Discover a world of enhanced features and show your support for our ongoing development with CyberPanel add-ons. Elevate your experience today!

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

  1. CMD

CMD provides the default arguments for running the container. However, there can only be one CMD or in case there are multiple CMDs, then only the last one takes effect. 

Syntax:

CMD [“nginx”, “-g”, “daemon off;”]

  1. LABEL

LABEL adds a metadata tag to the image, which includes all the important data, such as version info, description, and maintainer details. 

Syntax:

LABEL maintainer=”[email protected]

LABEL version=”1.0″

  1. EXPOSE

EXPOSE informs Docker about the ports that the container will listen in at runtime, but does not publish to the ports. 

Syntax:

EXPOSE 80 443

  1. ENV

ENV sets the environment variables inside the container. You can reference environment variables in later instructions using $APP_ENV.

Syntax:

ENV APP_ENV=production

  1. ADD vs COPY

 These two commands:

  • COPY copies files/directories from host to image — simple and predictable.
  • ADD does the same, plus it can extract archives and download URLs.

Syntax:

COPY ./src /app/src

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

  1. ENTRYPOINT

ENTRYPOINT defines a container’s main processes, which is ideal for setting main processes, unlike CMD, ENTRYPOINT arguments are not overridden at runtime.

Syntax:

ENTRYPOINT [“python3”, “app.py”]

  1. VOLUME

VOLUME creates a mount point with a specified path and marks it for the external volume sharing. Volumes persist data even if the container is deleted.

Syntax:

VOLUME /data

  1. WORKDIR

WORKDIR sets the working directory for any RUN, CMD, ENTRYPOINT, COPY, or ADD instructions that follow. Each WORKDIR builds on the previous one if relative paths are used.

Syntax:

WORKDIR /app

  1. ARG

 ARG defines a variable during the image build process, which is only available during the docker build, not runtime.
Syntax:

ARG APP_VERSION=1.0

RUN echo $APP_VERSION

  1. USER

USER sets the username or the userID to use when running the image. You can also run a non-root user to enhance container security. 

Syntax:

USER appuser

  1. HEALTHCHECK

HEALTHCHECK defines a command that Docker will use to check if the container is healthy. A failed health check marks the container as unhealthy, which is helpful for orchestration like Docker Swarm or Kubernetes. 

Syntax:

HEALTHCHECK CMD curl –fail http://localhost:80/ || exit 1

  1. ONBUILD

ONBUILD adds a trigger instruction to the images that executes when the image is used as a base for another build. It is essentially useful for creating base images that enforce certain behaviors for derived images.

Syntax:

ONBUILD COPY . /app/src

Common Mistakes to Avoid With Dockerfile Syntax

While using Dockerfile syntax, it is quite common to come across multiple bottlenecks, such as:

  1. Using Too Many Layers (RUN Statements)

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

  1. Not Using .dockerignore

Including unnecessary files (like .git, node_modules, etc.) bloats image size. Create a .dockerignore file to exclude them.

  1. Using ADD When COPY Is Sufficient

ADD has side effects (e.g., unpacking tarballs). Prefer COPY unless needed.

Related Article: Docker ADD vs COPY: Key Differences and Best Practices

  1. Running as root

Security risk: containers run as root by default. Use USER to switch to a non-root user.

  1. Hardcoding Secrets or API Keys

Never put secrets in ENV or RUN instructions. Use secrets management tools or Docker –build-arg carefully.

  1. Not Pinning Package Versions

Leads to unpredictable builds due to updated dependencies. Specify versions explicitly in RUN instructions.

IssuePossible CauseSolution
Build hangs or is slowLong-running RUN or large filesUse multi-stage builds and clean up cache
“File not found” errorsRelative paths not matchingUse WORKDIR properly and confirm paths exist
Ports not workingOnly EXPOSE usedUse -p flag when running: docker run -p 8080:80
Environment variable not availableConfusing ARG with ENVUse ENV for runtime, ARG for build time
Changes not reflecting in containerDocker cache using old layerUse –no-cache or reorder instructions to minimize cache issues
Permission deniedTrying to access files as wrong userSet correct ownership with USER or RUN chown

Wrapping Up – Dockerfile Syntax

Learning and understanding Dockerfile syntax is an essential step for automating Docker processes for image creation and more. This guide is your one step cheat sheet to refer to whenever you need quick help.

What are Dockerfile syntax for basic commands?

Key Dockerfile commands include FROMRUNCOPYADDCMDENTRYPOINT, and EXPOSE. These define the base image, install packages, copy files, and configure the container.

What’s the difference between CMD and ENTRYPOINT in Dockerfile?

CMD provides default arguments for the container, while ENTRYPOINT sets the main command to run. They can be used together, but ENTRYPOINT takes priority when both are present.

What is the best practice for writing a Dockerfile?

Best practices include using a minimal base image, combining RUN commands, minimizing the number of layers, cleaning up after installations, and avoiding storing secrets in the Dockerfile.

Marium Fahim
Hi! I am Marium, and I am a full-time content marketer fueled by an iced coffee. I mainly write about tech, and I absolutely love doing opinion-based pieces. Hit me up at [email protected].
Unlock Benefits

Become a Community Member

SIMPLIFY SETUP, MAXIMIZE EFFICIENCY!
Setting up CyberPanel is a breeze. We’ll handle the installation so you can concentrate on your website. Start now for a secure, stable, and blazing-fast performance!