6. Dockerfile Basics
Build a small web image and distinguish build-time and runtime instructions.
What Is a Dockerfile?
A Dockerfile describes how to build an image. Create an empty practice directory with these two files.
index.html:
<h1>Hello from the Docker course</h1>
Dockerfile:
FROM nginx:alpine
COPY index.html /usr/share/nginx/html/index.html
EXPOSE 80
The base image already defines how nginx starts. This example inherits that behavior.
Build and Run
Run these commands from the directory containing both files:
docker build -t docker-course-site:1 .
docker run -d --name docker-course-site -p 127.0.0.1:8081:80 docker-course-site:1
Visit http://localhost:8081 and confirm the heading.
Important Instructions
| Instruction | Purpose |
|---|---|
| FROM | Select a base image or begin a build stage |
| WORKDIR | Set the working directory |
| COPY | Copy files into the image |
| RUN | Execute a command during the build |
| CMD | Supply the default runtime command or arguments |
| ENTRYPOINT | Define the container executable |
| EXPOSE | Document a container port |
EXPOSE alone does not publish a port on the host.
Cleanup and Practice
docker stop docker-course-site
docker rm docker-course-site
Change the heading, rebuild with tag 2, and run the new image. Explain why changing a local file does not modify an already built image.
Quick Interview Answer
RUN executes while building an image. CMD and ENTRYPOINT determine what runs when a container starts.
Previous: 5. Images and Registries | Next: 7. Build Context and Cache
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form