Codementor Events

Serving Static Pages Using Nginx and Docker

Published Aug 11, 2018Last updated Feb 07, 2019

For most developers, the word NGINX has been mentioned or heard at one time or the other. NGINX is an open source software for web serving, reverse proxying, caching, load balancing, media streaming, and more. It started out as a web server designed for maximum performance and stability. In addition to its HTTP server capabilities, NGINX can also function as a proxy server for email (IMAP, POP3, and SMTP) and a reverse proxy and load balancer for HTTP, TCP, and UDP servers.

In this post, we will be setting up NGINX to serve sample static HTML pages. The whole setup will be built and packaged in a docker image. Lets get started.

First we create a folder say static_pages and in this folder we will create two folders named header and footer which will actually hold our static pages. Our folder structure should look like this


Our Folder Structure

The content of the index.html files for the header and footer respectively will just be a sample line as shown

<html>

<h1>I am the header</h1>

</html>
<html>

<h1>I am the footer</h1>

</html>

Now we create Dockerfile, mime.types and nginx.conf files. The Dockerfile is where we setup the docker configurations, mime.types is where we reference the type of static file we want NGINX to serve and the nginx.conf consist of our NGINX configuration settings. Our folder structure should now look like this

The Dockerfile will have these settings

FROM nginx

RUN rm -v /etc/nginx/nginx.conf

# Copy our nginx configuration file from the current directory

ADD nginx.conf /etc/nginx/

ADD header/src /usr/share/nginx/html/

ADD header /var/www/html/

ADD footer /usr/share/nginx/html/footer

# Expose ports

EXPOSE 8000

The mime.types ;

types {
  text/html html htm shtml;
  text/css css;
}

and finally the nginx.conf file;

worker_processes 1;

events { worker_connections 1024; }

http {

include mime.types;

sendfile on;

server {

listen 8000;

server_name localhost;

location /{

root /usr/share/nginx/html/;

index index.html;

}

location /footer/{

root /usr/share/nginx/html/;

expires 1y;

access_log off;

add_header Cache-Control "public";

}

}

}

You can add other file types to the mime.types file and also, the nginx.conf file can take more location directive or routes as you need.
Now we can go to the root directory of the project and build our docker image using this command docker build -t image_name . After successful build, we can run the docker image to start our NGINX server using this command docker run -p 8000:8000 image_name

Navigate to your browser and visit localhost:8000 to see the header.html file rendered and localhost:8000/footer to see the footer.html file rendered.

Leave questions, suggestions and observations in the comments.

Discover and read more posts from Dtemitope
get started
post commentsBe the first to share your opinion
Show more replies