DockerFile
Estimated reading: 4 minutes 37 views

🐳 Create a DockerFile – Step-by-Step Guide with Flask App Example


🧲 Introduction – Why Learn to Create a DockerFile?

In the age of containerization, Docker enables developers to build, ship, and run applications in isolated environments. But none of that is possible without a well-written DockerFileβ€”a simple script that defines everything needed to create a Docker image.

Creating a Docker image starts by writing a DockerFile with instructions on how to assemble your application environment. This file is the foundation of reproducible, automated deployments.

🎯 In this guide, you’ll learn:

  • βœ… What a DockerFile is and how it works
  • πŸ› οΈ How to write a DockerFile from scratch
  • πŸ§ͺ Real example using a Python Flask app
  • πŸ“ Best practices and tips
  • ❓ Answers to frequently asked questions

πŸ“¦ What is a DockerFile?

A DockerFile is a plain-text script that contains step-by-step instructions used by Docker to build a custom image. When you run docker build, Docker reads this file and executes each line to assemble the environment inside the image.

It’s the essential blueprint of every containerized application.


πŸ› οΈ Basic Structure of a DockerFile

Here’s a general structure of a DockerFile for any app:

# Base image
FROM ubuntu:20.04

# Maintainer info (optional)
LABEL maintainer="yourname@example.com"

# Install system dependencies
RUN apt-get update && apt-get install -y \
    python3 \
    python3-pip

# Set working directory
WORKDIR /app

# Copy files from host
COPY . /app

# Install Python packages
RUN pip3 install -r requirements.txt

# Expose port
EXPOSE 5000

# Default command to run the app
CMD ["python3", "app.py"]

This structure forms the backbone of your custom image.


πŸ” Explanation of Each DockerFile Instruction

πŸ”€ InstructionπŸ’¬ Description
FROMSets the base image (e.g., Ubuntu, Alpine, Node.js)
LABELAdds metadata like maintainer info
RUNExecutes commands at build time (e.g., install packages)
WORKDIRSets the working directory inside the container
COPYCopies files from host system into container
EXPOSEInforms Docker which port the app will use
CMDDefines the default runtime command for the container

πŸ§ͺ Example: Create a DockerFile for a Python Flask App

Let’s say you have a simple Flask project like this:

/flask-app
β”‚
β”œβ”€β”€ app.py
β”œβ”€β”€ requirements.txt
└── DockerFile

πŸ“„ app.py

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
    return "Hello from Docker!"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

πŸ“„ requirements.txt

Flask==2.1.2

πŸ“„ DockerFile

# Base image with Python
FROM python:3.9-slim

# Set working directory
WORKDIR /app

# Copy requirements first
COPY requirements.txt requirements.txt

# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Copy all app files
COPY . .

# Expose port for Flask
EXPOSE 5000

# Default run command
CMD ["python", "app.py"]

▢️ Build and Run the Docker Image

πŸ”§ Step 1: Build the Docker Image

docker build -t flask-app .
  • -t names the image as flask-app
  • . points to the current directory as context

▢️ Step 2: Run the Docker Container

docker run -p 5000:5000 flask-app

πŸ”— Open http://localhost:5000 in your browser, and you’ll see:
“Hello from Docker!”


πŸ’‘ Best Practices for Writing DockerFiles

βœ… Best PracticeπŸ“Œ Why It Matters
Use slim/minimal imagesReduces size and speeds up builds (e.g., python:3.9-slim)
Combine RUN commandsMinimizes image layers and build time
Use .dockerignorePrevents unnecessary files from bloating your image
Never hardcode secretsUse ENV or runtime variables; never write passwords/API keys
Install only required packagesKeep your image lean and secure
Tag your imagesUse meaningful tags like my-app:latest, my-app:v1.0 for versioning

πŸ“Œ Summary – Recap & Next Steps

Creating a DockerFile is the first step in building any Docker image. By writing clean, optimized instructions, you ensure that your apps run consistently across all environmentsβ€”from development to production.

πŸ” Key Takeaways:

  • DockerFile is a build script that defines how your image is created.
  • Use instructions like FROM, COPY, RUN, and CMD appropriately.
  • Build with docker build, and run with docker run.
  • Use best practices for clean, efficient, and secure images.

βš™οΈ Next Steps:

Try writing a DockerFile for your own app, integrate it with CI/CD, or experiment with multi-stage builds for production-ready images.


❓ Frequently Asked Questions (FAQ)


πŸ”„ What’s the difference between CMD and ENTRYPOINT?
βœ… CMD sets default arguments; ENTRYPOINT sets the main executable.
You can use both together for flexible container behavior.


πŸ” Can I pass environment variables in a DockerFile?
βœ… Yes. Use ENV for static values:

ENV API_KEY=12345

Override at runtime with -e:

docker run -e API_KEY=67890 my-image

🧹 How do I reduce Docker image size?

  • Use slim/minimal base images
  • Avoid unnecessary packages
  • Clean cache and temporary files with --no-cache

πŸ” How do I rebuild an image after changes?
Use --no-cache to force a clean build:

docker build --no-cache -t my-image .

πŸ›‘ Why isn’t my CMD or ENTRYPOINT working?

  • Ensure you’re using the correct JSON array syntax:
    ["python", "app.py"]
  • Avoid mixing conflicting commands in CMD and ENTRYPOINT

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

How to Create a DockerFile to Build an Image

Or Copy Link

CONTENTS
Scroll to Top