Build & Run an Nginx Container
Today I practiced creating a simple Docker image using Nginx and running it as an isolated container. Here is my step-by-step process, the code used, and the crucial troubleshooting lessons I learned along the way.
The Dockerfile
FROM nginx
WORKDIR /usr/share/nginx/html
COPY index.html /usr/share/nginx/html
EXPOSE 80Instruction Breakdown
- FROM Uses the official Nginx image from Docker Hub as the starting base image.
- WORKDIR Sets the working directory inside the container where the website files will be stored natively by Nginx.
- COPY Copies the local
index.htmlfile from your host system into the Nginx web directory inside the container. - EXPOSE Documents that the container application listens on port 80. (Note: this does not publish the port, it's just documentation).
Build and Run the Container
After creating the Dockerfile, the next step is to build the image locally and execute it. We will map port 88 on our host machine to port 80 inside the container.
Run Options Explained
- -d Runs the container in detached mode (in the background).
- -p 88:80 Port Mapping: Maps host port 88 to container port 80.
- --name shan Assigns a friendly, memorable name to the running container.
- shan The name of the Docker image we just built to run.
terminal
# 1. Build the Docker Image
# (Builds image using Dockerfile in current dir and tags it 'shan')
$ docker build -t shan .
Successfully built image 'shan'
# 2. Run the Docker Container
$ docker run -d -p 88:80 --name shan shan
a1b2c3d4e5f6...
# 3. Access the Website
Open your browser and navigate to:
$ http://localhost:88Troubleshooting & Mistakes
While completing this task, I made a few mistakes. Debugging them taught me some of the most important rules of Docker operations.
What I Learned
Image Definition
Dockerfile instructions explicitly define exactly how the image is built, layer by layer.
Ports & EXPOSE
EXPOSE only documents container ports for developers. Actual port mapping is done using docker run -p.
Internal Alignment
Application ports and file paths mapped inside containers must strictly match the default configuration of the service (like Nginx) running inside.