100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
HomeBlogWhat Is a Dockerfile and How to Write One
Cloud & Cybersecurity

What Is a Dockerfile and How to Write One

SV

SkillVeris Team

Cloud & Security Team

May 29, 2025 9 min read
Share:
What Is a Dockerfile and How to Write One
Key Takeaway

A Dockerfile is a text file of instructions that Docker follows step by step to build a container image.

In this guide, you'll learn:

  • Each instruction creates a cached layer, so ordering them well makes rebuilds dramatically faster.
  • Core instructions are FROM, WORKDIR, COPY, RUN, EXPOSE, and CMD, run top to bottom.
  • Copy dependency files and install before copying your source to get the most out of build caching.
  • Multi-stage builds keep the final image small by leaving build tools behind.

1What Is a Dockerfile?

A Dockerfile is a plain text file containing a sequence of instructions that Docker executes in order to assemble a container image. Think of it as a repeatable recipe: it starts from a base image, adds your code and dependencies, and specifies how the container should run.

Because the build is scripted, anyone with the Dockerfile can produce the exact same image. That reproducibility is the whole point — the environment stops being something you set up by hand and becomes something you build from code.

2How a Build Works

When you run docker build, Docker reads the Dockerfile top to bottom, executing each instruction and saving the result as a layer. Stacked together, those layers form the final image.

  • Each instruction produces a new read-only layer on top of the previous one.
  • Docker caches each layer and reuses it if nothing that affects it has changed.
  • If a layer changes, that layer and every layer after it must be rebuilt.
  • The final image is the stack of all layers plus a thin writable layer at runtime.

🔑Key Idea

Layer caching is the single biggest lever on build speed. Order instructions so the things that rarely change come first and the things that change often (your source code) come last.

3Core Instructions

A handful of instructions appear in nearly every Dockerfile. Learn these and you can read and write most of them.

  • FROM = the base image to build on (e.g. python:3.12-slim).
  • WORKDIR = set the working directory for later instructions.
  • COPY = copy files from your machine into the image.
  • RUN = execute a command at build time (install dependencies).
  • EXPOSE = document the port the app listens on.
  • CMD = the default command to run when the container starts.

CMD vs RUN

RUN executes during the build to create the image — for example installing packages. CMD does not run at build time; it defines what happens when the finished container starts. Mixing them up is a common beginner error.

4A Complete Example

Here is a practical Dockerfile for a Python web app. Notice the ordering: dependencies are installed before the source is copied, so editing your code does not bust the dependency cache.

  • FROM python:3.12-slim
  • WORKDIR /app
  • COPY requirements.txt .
  • RUN pip install --no-cache-dir -r requirements.txt
  • COPY . .
  • EXPOSE 8000
  • CMD ["gunicorn", "-b", "0.0.0.0:8000", "app:app"]

💡Pro Tip

Copy requirements.txt and install dependencies before copying the rest of your code. Since dependencies change less often than source, Docker reuses the cached install on most rebuilds, saving significant time.

5Making the Most of Layer Caching

Build caching is what separates a two-second rebuild from a two-minute one. The rule is simple: put stable instructions high and volatile ones low.

When you change your source code, Docker only needs to rebuild from the COPY . . step onward — the base image and installed dependencies above it are reused from cache. Reverse that order and every code edit reinstalls all dependencies.

  • Put FROM and dependency installation near the top.
  • Copy only the dependency manifest first, then install.
  • Copy the full source afterward, since it changes most often.
  • Combine related RUN commands to reduce layer count where sensible.

6Multi-Stage Builds

A multi-stage build uses more than one FROM to separate the build environment from the final runtime image. You compile or install in a build stage, then copy only the finished artifacts into a slim final stage.

The result is a much smaller image because compilers, build tools, and dev dependencies are left behind. Smaller images pull faster, start quicker, and have a smaller attack surface.

  • FROM node:20 AS build
  • WORKDIR /app
  • COPY . .
  • RUN npm ci && npm run build
  • FROM nginx:alpine
  • COPY --from=build /app/dist /usr/share/nginx/html

7Best Practices

A few habits produce Dockerfiles that build fast and run safely.

  • Use small base images like -slim or -alpine variants where possible.
  • Add a .dockerignore so build context stays small and secrets are excluded.
  • Pin image tags (python:3.12-slim, not python:latest) for reproducible builds.
  • Run as a non-root user with a USER instruction for better security.
  • Use multi-stage builds to keep the final image lean.

⚠️Watch Out

Never bake secrets like API keys or passwords into a Dockerfile with COPY or ENV. They persist in the image layers and can be extracted by anyone who pulls it. Pass secrets at runtime instead.

8Common Mistakes to Avoid

Most Dockerfile problems come from a short list of habits.

  • Copying all source before installing dependencies, so every edit rebuilds everything.
  • Using a full base image when a slim variant would do, bloating the image.
  • Forgetting a .dockerignore, sending node_modules and secrets into the build context.
  • Baking secrets into layers with ENV or COPY where they can be recovered.

9Key Takeaways

The essentials of writing a Dockerfile come down to a few points.

  • A Dockerfile is a scripted recipe that builds a reproducible container image.
  • Each instruction is a cached layer; order stable steps first, volatile ones last.
  • Core instructions are FROM, WORKDIR, COPY, RUN, EXPOSE, and CMD.
  • Install dependencies before copying source to maximise cache reuse.
  • Use multi-stage builds, slim base images, and a non-root user for small, secure images.

10Frequently Asked Questions

Q: What is the difference between an image and a container? A: An image is the built, read-only template produced from a Dockerfile. A container is a running instance of that image. One image can start many containers, just as one class can create many objects.

Q: What is the difference between CMD and RUN? A: RUN executes during the build to create the image, such as installing packages. CMD defines the default command that runs when the container starts. RUN shapes the image; CMD shapes runtime behaviour.

Q: Why is my Docker build so slow? A: Usually because instructions are ordered badly. If you copy all source before installing dependencies, any code change invalidates the cache and reinstalls everything. Copy the dependency manifest and install first.

Q: What is a multi-stage build? A: It uses multiple FROM stages so you can build in one environment and copy only the finished artifacts into a slim final image, leaving compilers and dev tools behind for a smaller, safer result.

📄

Get The Print Version

Download a PDF of this article for offline reading.

About the Publisher

SV

SkillVeris Team

Cloud & Security Team

Our cloud and security experts break down complex infrastructure topics into practical, beginner-friendly guides.

View all posts

Never miss an update

Get the latest tutorials and guides delivered to your inbox.

No spam. Unsubscribe anytime.

Frequently Asked Questions

21 categories · pick one to explore

Does SkillVeris have a tech blog, and what does it cover?
Yes, the SkillVeris blog has over 500 articles covering AI and machine learning, programming, web development, DevOps, cloud, security, databases and career guidance. Articles are practical and answer-first, and many use the Learn Through Hobbies approach, teaching technical concepts through cricket, music, gaming or cooking analogies. Everything is free to read.
What is the SkillVeris tech glossary and how big is it?
The SkillVeris glossary is a free reference of roughly 2,000-plus technology terms, each with a clear plain-language definition. It spans AI, programming, web, DevOps, cloud, security and database vocabulary, so whenever a lesson, article or job description uses jargon you do not recognise, the glossary gives you a fast, reliable answer.
Are the developer cheat sheets on SkillVeris free to download?
The cheat sheets are completely free to use, like everything else on SkillVeris. Each sheet condenses a language or tool into its essential syntax, commands and patterns for quick reference while coding. They are designed for rapid lookup during real work, complementing the deeper explanations found in study notes and courses.
Which programming references and cheat sheets are available?
Cheat sheets cover the platform's main domains, including programming languages, AI and ML tooling, web development, DevOps, cloud, security and databases, matching the topics of the 37 live courses. Each sheet lists related reading links and hashtags, so you can jump from a quick reference into fuller study notes or blog articles.
How do I find the meaning of a technical term quickly?
Search the SkillVeris glossary, which holds around 2,000-plus terms with concise, plain-language definitions. Each entry gets to the point in its first sentence, then links to related reading like blog posts or study notes for deeper context. It is faster and more consistent than sifting through scattered search results.
Is the SkillVeris blog good for beginners learning to code?
Yes, many blog articles are written specifically for beginners, and the Learn Through Hobbies style makes them unusually approachable: you might learn Python concepts through cricket or understand APIs through cooking. With 500-plus articles across skill levels, beginners can start with fundamentals and keep reading as they advance, entirely free.
Can cheat sheets replace full courses for learning a language?
No, cheat sheets are references, not teaching tools; they assume you already understand the concepts and just need syntax or commands fast. To actually learn a language, take a structured SkillVeris course with its 24–40 lessons and assessments, then keep the cheat sheet beside you while practising in Code Lab.
How often are new blog articles published on SkillVeris?
The blog grows regularly and already exceeds 500 articles, with new posts added as courses launch and technologies evolve. Topics track the platform's catalogue across AI, programming, web development, DevOps, cloud and security, so checking the Blog section periodically surfaces fresh tutorials, explainers and career-focused pieces, all free to read.
Does the glossary cover AI and machine learning terms?
Yes, AI and machine learning vocabulary is a major part of the roughly 2,000-plus term glossary, covering everything from foundational terms to modern concepts around LLMs, RAG and MLOps. Definitions are plain-language and answer-first, which helps when dense AI papers or course lessons throw unfamiliar jargon at you.
Are there cheat sheets for interview preparation?
Cheat sheets work well as interview-day refreshers because they compress syntax, commands and key concepts into scannable references. For dedicated preparation, combine them with the SkillVeris interview questions feature, which includes readiness scoring, plus study notes for depth. Reviewing a relevant cheat sheet just before an interview steadies recall under pressure.
Can I read the tech blog without signing up?
Yes, the blog is freely readable, and SkillVeris never charges for content. All 500-plus articles are open, covering tutorials, concept explainers and career advice. Creating a free account adds value elsewhere on the platform, like course progress tracking and certificates, but reading the blog requires no commitment at all.
How is the SkillVeris glossary different from Wikipedia?
The glossary is purpose-built for learners: definitions are short, plain-language and answer-first, sized for a quick lookup mid-lesson rather than a deep encyclopedic read. Entries also cross-link to related SkillVeris study notes, blog posts and courses, so a definition becomes a doorway into structured learning instead of a dead end.
Do blog articles use the Learn Through Hobbies method?
Many blog articles teach technical topics through hobby analogies, a hallmark of the SkillVeris blog, so you will find articles explaining programming through cricket, machine learning through music, or system design through cooking. The analogy is the teaching device; the article still delivers the real technical concept underneath.
Where can I find quick programming references while coding?
Open the SkillVeris cheat sheets, which are built exactly for that moment: compact, scannable references for syntax, commands and common patterns across languages and tools. Keep the relevant sheet in a browser tab while you work in Code Lab or your own editor, and dip into the glossary for terminology.
Is there a glossary entry for terms I meet in job descriptions?
Very likely yes, with roughly 2,000-plus terms across AI, programming, web, DevOps, cloud, security and databases, the glossary covers most jargon that appears in tech job descriptions. Decoding a listing this way helps you judge role fit honestly and prepares you to discuss those terms in interviews.
Are the blog articles written for the Indian tech audience?
The blog serves Indian learners plus a worldwide audience. Content stays globally relevant while acknowledging realities that matter in India, such as free access being essential for students and freshers, and career guidance that connects naturally to the SkillVeris jobs portal, which aggregates roles across India, UK, USA, Germany and Remote.
Can I suggest a topic for the blog or glossary?
SkillVeris content grows in response to what learners need, so feedback is welcome through the platform's support channels. If a term is missing from the glossary or a topic deserves an article, telling the team helps prioritise it. Meanwhile, the AI Mentor can answer the question immediately, 24/7, at any depth.
Do cheat sheets and glossary entries link to deeper learning?
Yes, every cheat sheet and glossary entry carries related reading links into study notes, blog articles and courses, plus concept hashtags for discovering similar content. This cross-linking means a thirty-second lookup can smoothly become a structured learning session whenever you decide you want more than a quick answer.
What makes SkillVeris programming references trustworthy?
The references are written to strict internal quality standards, kept consistent with the platform's 37 live courses, and never padded with invented statistics or hype. Definitions and cheat sheets are reviewed against the same content contracts that govern courses, and the answer-first style makes any inaccuracy easy to spot and correct.
How do the blog, glossary and cheat sheets fit into my learning routine?
Use them as satellites around your main course: read blog articles for context and motivation, hit the glossary the instant jargon appears, and keep cheat sheets open while coding. Together with study notes, Code Lab and the 24/7 AI Mentor, they turn passive reading into a complete, free learning system.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse