πŸ›³οΈ Docker Series: Episode 4 β€” Dockerfile for Beginners: Build Your Own Container Image



This content originally appeared on DEV Community and was authored by Yash Sonawane

🎬 “Ready to become a Docker chef? In this episode, we’ll write your first Dockerfile β€” the recipe that creates your own custom container. Simple, step-by-step, with a real app. Let’s cook! 👨‍🍳🍱

🍳 What is a Dockerfile?

A Dockerfile is like a recipe card for Docker. It tells Docker exactly how to build an image from scratch.

Just like:

  • A cake recipe includes ingredients and steps
  • A Dockerfile includes base image, dependencies, code, and commands

Once Docker reads the Dockerfile, it builds a Docker image, which you can then run as a container.

👨‍💻 Let’s Build Your First Dockerfile

We’ll dockerize a basic Node.js app.

📁 Project Structure:

my-node-app/
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ package.json
└── index.js

🧠 index.js (your app):

const http = require('http');

const server = http.createServer((req, res) => {
  res.end('Hello from Docker!');
});

server.listen(3000, () => console.log('Server running on port 3000'));

📦 package.json:

{
  "name": "my-node-app",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  }
}

🛠 Writing the Dockerfile

Now create a file called Dockerfile (no extension!) and add this:

# Base image
FROM node:18

# Working directory
WORKDIR /app

# Copy files
COPY package*.json ./

# Install dependencies
RUN npm install

# Copy app source
COPY . .

# Expose port
EXPOSE 3000

# Start the app
CMD ["npm", "start"]

🧪 Build & Run the Docker Image

🔨 Build the image:

docker build -t my-node-app .

🚀 Run the container:

docker run -d -p 3000:3000 my-node-app

🌐 Open your browser:

Visit http://localhost:3000 β€” you’ll see: Hello from Docker!

🧠 What Did We Just Do?

  • FROM: Sets the base environment (Node.js)
  • WORKDIR: The folder where your code lives inside the container
  • COPY: Moves your code into the container
  • RUN: Installs dependencies
  • EXPOSE: Lets Docker know what port the app uses
  • CMD: Tells Docker how to start the app

🛡 Bonus Tips

  • Use .dockerignore to skip node_modules, logs, etc.
  • Always pin your base image (node:18 not just node)
  • Keep Dockerfiles short, clean, and readable

🎯 Up Next: Docker CLI Mastery

In Episode 5, we’ll explore:

  • Most used Docker commands
  • How to manage images and containers
  • Tricks to make your Docker life easier

💬 Let’s Build Together

Have you written your first Dockerfile? Did it work? Run into any errors?

Comment below β€” I’m here to help every beginner succeed 🚀

❤ If you learned something new today, show some love with a like or drop a comment. Share this episode with your Dev.to fam!

🎬 Next: β€œDocker CLI Cheat Sheet β€” 15 Commands You’ll Actually Use”


This content originally appeared on DEV Community and was authored by Yash Sonawane