Hosting a static site using Nginx web server inside Docker container

Nitish
Code To Express
Published in
3 min readJun 3, 2019
Nginx is the second most popular Web server in the world ;)

In this tutorial, We’ll see an example of hosting a static website using Nginx web server inside a Docker container.

I assume that you already know the basics of Docker, and have it installed on your computer. If you haven’t any idea about containerisation, then you can refer to this blog- Installation and Getting started with docker.

Docker Images are built based on the contents of a Dockerfile. The Dockerfile is a list of instructions describing how to build a Docker image.

Here, We’ll be using Ubuntu as the base image. You can also use other distributions or default nginx base image. Further, We’ll copy our simple index.html file inside the container. While the CMD is used to provide defaults when executing a container.

Dockerfile

Let’s create a simple index.html which we’ll be hosting further through Nginx using docker container.

index.html

Now we can build our Dockerfile by running the following command, Docker will then generate an image based on our Dockerfile.

docker build -t <image-name> .
  • Here, -t option is used to assign a name-tag to the docker images.
  • In the end, we give the path of the Dockerfile using which we want to build the Docker image.

This will produce the following output.

Building Docker images using Dockerfile

Note: It can take some time, depending on your Wi-Fi speed for downloading the base image.

We can check if the docker image is built successfully by running the command,

docker images

This command should produce the following output.

List all docker images

Now, we’ll use the same image to create a running container by using the following command.

docker run -d --name <container-name> <image-name>

Explanation of this command is as below,

  • -d option is used to run a container in background and print container ID.
  • --name option is used to assign a name to the container.
  • -p option is used for port mapping between container and Host machine.
  • In the end, we provide the name of the docker image from which we wish to run our container.

Now, We can see the running containers by using the following command,

docker ps

The result of this command should be as follow:

Running a container and listing all running containers

This will start serving the static site on port 8000. If you visit http://localhost:8000 in your browser, you should be able to see our static site!

Want me to write more!

Hit claps if you liked it. It will encourage me to write more. Follow me for more interesting posts. Comment below if you have any other questions and inputs.

--

--

Nitish
Code To Express

DevOps Engineer👨‍💻 Hobby photographer 📸 Learning about Investing 📈