Whitefield, Bangalore +91 9491996396 Office Hours: 8AM - 5PM Sunday - Wekend Day
December 4, 2023 No Comments

Build a Docker image for Nginx Web Server

Basic example of a Dockerfile for building a Docker image for the Nginx web server:

# Use an official Nginx base image
FROM nginx:latest

# Set the working directory to the Nginx document root
WORKDIR /usr/share/nginx/html

# Copy the contents of the local "html" directory to the container
COPY html/ .

# Expose port 80 for incoming web traffic

# Start the Nginx server when the container starts
CMD ["nginx", "-g", "daemon off;"]

Brief explanation of each section:

  1. FROM nginx:latest: This line specifies the base image to use for building the new image. In this case, it uses the latest official Nginx image from the Docker Hub.
  2. WORKDIR /usr/share/nginx/html: Sets the working directory within the container to the Nginx document root.
  3. COPY html/ .: Copies the contents of the local “html” directory (assuming you have a directory named “html” in the same directory as the Dockerfile) to the container’s document root.
  4. EXPOSE 80: Informs Docker that the container will listen on port 80 at runtime.
  5. CMD ["nginx", "-g", "daemon off;"]: Specifies the default command to run when the container starts. In this case, it starts the Nginx server and runs it in the foreground.

To build the Docker image, save the above content in a file named Dockerfile, and place it in a directory that contains your html directory (with your web content). Then, run the following command in the same directory as your Dockerfile:

docker build -t my-nginx-image .

This command builds a Docker image with the tag my-nginx-image using the current directory as the build context. After the build is complete, you can run a container based on this image:

docker run -p 8080:80 my-nginx-image

This command maps port 8080 on your local machine to port 80 on the Docker container. You can access the Nginx server by visiting http://localhost:8080 in your web browser.

Leave a Reply

Your email address will not be published. Required fields are marked *




Welcome to iTechMentors - Online IT Courses Training Institute

× How can I help you?