What is a Dockerfile?
A Dockerfile is a plain text file that contains a set of instructions to build a Docker image. Each instruction in a Dockerfile creates a new layer in the image.
Docker reads the Dockerfile from top to bottom and executes each instruction to assemble the final image.
Common Dockerfile Instructions
| Instruction | Description |
|---|---|
FROM |
Base image to start from |
RUN |
Execute command during image build |
COPY |
Copy files from host into image |
ADD |
Like COPY but supports URLs and tar extraction |
WORKDIR |
Set working directory inside container |
CMD |
Default command when container starts |
ENTRYPOINT |
Fixed command (CMD provides arguments) |
EXPOSE |
Document the port the container listens on |
ENV |
Set environment variables |
ARG |
Build-time variable |
VOLUME |
Create a mount point |
Example 1: Simple Dockerfile for a Node.js App
# Step 1: Use official Node.js base image
FROM node:18-alpine
# Step 2: Set working directory inside container
WORKDIR /app
# Step 3: Copy package.json first (for layer caching)
COPY package.json .
# Step 4: Install dependencies
RUN npm install
# Step 5: Copy all source files
COPY . .
# Step 6: Expose port
EXPOSE 3000
# Step 7: Start the application
CMD ["node", "index.js"]
Build and run:
docker build -t my-node-app .
docker run -d -p 3000:3000 my-node-appExample 2: Dockerfile for PHP App
FROM php:8.2-apache
WORKDIR /var/www/html
COPY . .
EXPOSE 80
CMD ["apache2-foreground"]
docker build -t my-php-app .
docker run -d -p 8080:80 my-php-app
Example 3: Dockerfile with ENV and ARG
FROM ubuntu:22.04
# Build-time argument
ARG APP_VERSION=1.0
# Runtime environment variable
ENV APP_ENV=production
ENV APP_NAME=OnlineLearner
RUN echo "Building version $APP_VERSION"
CMD ["bash"]
# Pass build argument
docker build --build-arg APP_VERSION=2.0 -t myapp .
CMD vs ENTRYPOINT
| Feature | CMD | ENTRYPOINT |
|---|---|---|
| Purpose | Default arguments | Fixed executable |
| Override | Can be overridden at runtime | Cannot be overridden easily |
| Use Case | Default command | Always-run executable |
# CMD example
CMD ["nginx", "-g", "daemon off;"]
# ENTRYPOINT example
ENTRYPOINT ["nginx"]
CMD ["-g", "daemon off;"]Best Practices
- Use small base images like
alpineto reduce image size. - Place
COPY package.jsonandRUN npm installbefore copying source code — this caches dependencies. - Use
.dockerignorefile to exclude unnecessary files. - One process per container — keep containers focused.
Summary
- A Dockerfile is a script of instructions to build a Docker image.
- Key instructions:
FROM,RUN,COPY,WORKDIR,CMD,EXPOSE. - Use
docker build -t name .to build the image from the Dockerfile.
0
likes
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
