Hosting a static site using Nginx web server inside Docker container
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 containerization, 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. Further, We’ll copy our simple index.html file inside the container. While the CMD is used to provide defaults when executing a container. You can explore more about writing Dockerfiles from Here.
Here’s the Dockerfile we’re using!
Let’s create a simple index.html which we’ll be hosting further through Nginx using docker container.
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.
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,
This command should produce the following output.
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,
The result of this command should be as follow:
This will start serving the static site on port 8000. If you visit
http://localhost:8000in 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.