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
RUNcommands 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
| Instruction | Purpose |
|---|---|
| FROM | Sets the base image for your Docker image |
| RUN | Executes commands during image build |
| COPY | Copies files from host to image |
| CMD | Specifies the default command to run in the container |
| EXPOSE | Documents the port the container listens on |
| ENV | Sets 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.