Dockerfile Explained: How to Build Custom Docker Images
Dockerfiles are the foundation for creating your own Docker images. Instead of downloading pre-made containers, you can define exactly what you need — from system packages to application code — all in a single file. Let’s learn how to build custom docker images step by step.
What is a Dockerfile?
A Dockerfile is a plain text file that contains instructions to build a Docker image. Each line in the file is a command that defines what your environment should look like.
It’s like writing a recipe for your app environment — once defined, you can rebuild it anytime, anywhere.
Steps To Build Custom Docker Images
Simple Example: Building a Python App
Let’s say you have a basic Python app (app.py
) with this content:
# app.py
print("Hello from Docker!")

Now, here’s how to write a Dockerfile to run this app:
# Use the official Python base image
FROM python:3.10-slim
# Set the working directory inside the container
WORKDIR /app
# Copy the app.py file to the container
COPY app.py .
# Define the default command to run
CMD ["python", "app.py"]

Make sure the folder structure is as follows:
your-folder/
├── Dockerfile
└── app.py
Step-by-Step Explanation
Line | Purpose |
FROM | Sets the base image (in this case, Python 3.10) |
WORKDIR | Sets /app as the working directory inside the container |
COPY | Copies the app.py file into the container |
CMD | Tells Docker what to run when the container starts |
How to Build the Image
In the same directory as your Dockerfile
and app.py
, run:
docker build -t my-python-app .

This command builds a Docker image called my-python-app
.
Run the Container
Now let’s run it:
docker run my-python-app
Expected output:
Hello from Docker!

Tips for Custom Dockerfiles
- Use
.dockerignore
to exclude files/folders from your image (like.git
,__pycache__
, etc.) - Use
RUN
for installing dependencies, e.g.:
RUN pip install requests
- Combine layers for efficiency:
RUN apt-get update && apt-get install -y curl
Clean Up (Optional)
Remove the container after testing:
docker container prune
Remove the image if no longer needed:
docker rmi my-python-app
Dockerfiles give you full control over your application environment, making it easy to share, deploy, and scale. With just a few lines, you can build custom containers tailored to your project’s needs.
You can read more useful articles like How To Install Docker On Ubuntu.
Follow us for the more helpful posts!
We hope this is a useful post for you.
Thank you for reading!