0
0
DockerHow-ToBeginner · 3 min read

How to Create a Dockerfile: Simple Guide with Example

To create a Dockerfile, write a plain text file named Dockerfile that contains instructions like FROM, RUN, and CMD to define your container image. Save it in your project folder and build the image using docker build.
📐

Syntax

A Dockerfile uses simple instructions to build a container image. Key instructions include:

  • FROM: sets the base image.
  • RUN: runs commands inside the image during build.
  • COPY: copies files from your computer into the image.
  • CMD: sets the default command to run when the container starts.
dockerfile
FROM <base_image>
RUN <command>
COPY <source> <destination>
CMD ["executable", "param1", "param2"]
💻

Example

This example creates a Docker image that uses the official python:3.11-slim base image, copies a script, and runs it by default.

dockerfile
FROM python:3.11-slim
COPY hello.py /app/hello.py
CMD ["python", "/app/hello.py"]
Output
Hello from Docker!
⚠️

Common Pitfalls

Common mistakes when creating Dockerfiles include:

  • Not naming the file exactly Dockerfile (case sensitive).
  • Forgetting to specify a base image with FROM.
  • Using RUN commands that require interactive input.
  • Not using JSON array syntax for CMD, which can cause unexpected behavior.
dockerfile
### Wrong CMD syntax (string form, can cause issues)
CMD "python /app/hello.py"

### Correct CMD syntax (JSON array form)
CMD ["python", "/app/hello.py"]
📊

Quick Reference

InstructionPurpose
FROMSets the base image for your Docker image
RUNExecutes commands during image build
COPYCopies files from host to image
CMDSpecifies the default command to run in the container
EXPOSEDocuments the port the container listens on
ENVSets environment variables inside the image

Key Takeaways

Always start your Dockerfile with a FROM instruction to set the base image.
Use COPY to add your application files into the image.
Use CMD with JSON array syntax to define the container's default command.
Name the file exactly Dockerfile with no extension and place it in your project folder.
Build your image with docker build -t yourimagename . from the folder containing the Dockerfile.