Learn Nginx · 13/13

Nginx in Modern Infrastructure (Docker)

9 min read

Nginx in Modern Infrastructure (Docker)

Welcome, future DevOps maestro! ოს Today, we're diving into the wonderful world of Nginx and Docker. It's like putting a superhero in a super-suit – Nginx is already powerful, but with Docker, it becomes an unstoppable force in modern web infrastructure.

So, grab your favorite beverage, and let's get this container party started!


1. Containerizing Nginx: Writing and Understanding the Dockerfile 🐳

The "What" and "Why"

What is Containerizing Nginx?

Simply put, it's the process of packaging your Nginx web server and all its configurations, dependencies, and code into a neat, isolated box called a Docker container. This container can run on any machine that has Docker installed, regardless of the underlying operating system.

The Problem It Solves

Imagine you've meticulously configured Nginx on your trusty old laptop. It works perfectly! Now, you need to deploy it to a production server. You cross your fingers, hope everything is the same, but... it breaks. 😱 Maybe the server has a different operating system, a conflicting library, or a slightly different configuration. This is affectionately known as the "it works on my machine" syndrome, a programmer's ancient curse.

How Docker Solves It

Docker containers are like self-contained apartments for your applications. Everything Nginx needs to run is bundled inside – the right operating system, the correct libraries, your specific configurations. You build this "apartment" once and can then move it to any "building" (any machine with Docker) without worrying about the neighbors (other applications) or the building's quirky plumbing (the host OS). This ensures consistency and reliability from development to production.

Writing Your First Nginx Dockerfile

A Dockerfile is a recipe for building a Docker image. It's a simple text file with a set of instructions. Let's create a basic one for Nginx.

Step 1: The FROM Instruction - Choosing Your Base

Every Docker image is built on top of another image. We'll start with an official Nginx image from Docker Hub. It's like choosing the foundation for your house.

dockerfile
# Use an official Nginx runtime as a parent image
FROM nginx:latest

Think of it as saying, "Hey Docker, I want to start with a fresh installation of the latest Nginx."

Interesting Fact: The nginx:latest tag points to the most recent stable version of Nginx. For production, it's often better to use a specific version like nginx:1.25.3 to avoid unexpected updates.

Step 2: The COPY Instruction - Adding Your Files

Now, let's add our own custom HTML file to be served by Nginx. Let's say we have an index.html file in the same directory as our Dockerfile.

dockerfile
# Use an official Nginx runtime as a parent image
FROM nginx:latest

# Copy a custom index.html file to the Nginx html directory
COPY index.html /usr/share/nginx/html/index.html

The COPY instruction tells Docker to take our local index.html and place it inside the container at the specified path, which is the default location Nginx serves files from.

Step 3: The EXPOSE Instruction - Opening the Doors

We need to tell Docker which ports our container will listen on. Nginx, by default, listens on port 80 for HTTP traffic.

dockerfile
# Use an official Nginx runtime as a parent image
FROM nginx:latest

# Copy a custom index.html file to the Nginx html directory
COPY index.html /usr/share/nginx/html/index.html

# Inform Docker that the container is listening on port 80
EXPOSE 80

This is like putting a sign on your apartment door saying, "Pizza deliveries welcome at this door!" It doesn't actually open the door to the outside world, but it documents which port the application inside is using.

Building and Running the Container

Now for the magic! Open your terminal in the directory where your Dockerfile and index.html are.

  1. Build the image:

    bash
    docker build -t my-custom-nginx .

    The -t flag tags our image with a memorable name. The . at the end tells Docker to look for the Dockerfile in the current directory.

  2. Run the container:

    bash
    docker run -d -p 8080:80 my-custom-nginx
    • -d runs the container in detached mode (in the background).
    • -p 8080:80 maps port 8080 on your host machine to port 80 inside the container. This is what actually opens the door to the outside world.

Now, open your web browser and navigate to http://localhost:8080. You should see your custom index.html! 🎉

Under the Hood: When you run the container, Docker creates an isolated environment. It pulls the nginx:latest image if you don't have it, then applies your COPY instruction. Finally, it starts the Nginx process inside the container, which then listens on port 80 within its isolated network. The port mapping you provided connects your host machine's port 8080 to the container's port 80, allowing you to access it.


2. Managing Nginx Configurations via Docker Volumes 💾

The "What" and "Why"

What are Docker Volumes?

Docker volumes are the preferred way to persist data generated by and used by Docker containers. Think of them as a dedicated, managed storage space for your container's data that lives outside the container itself.

The Problem It Solves

Containers are designed to be ephemeral, meaning they can be stopped, destroyed, and replaced at any time. This is great for stateless applications, but what about our Nginx configuration files? If we store them inside the container, they'll be gone forever when the container is removed. We'd have to rebuild the image every time we want to change a single line in our configuration. That's like having to rebuild your entire house just to change a lightbulb! 💡

How Volumes Solve It

Volumes allow you to store your Nginx configuration files on the host machine and "mount" them into the container. This means the container can read and use these files, but they don't live inside the container's disposable file system. You can update your Nginx configuration on your host, and the changes will be reflected in the running container without needing to rebuild the image.

Using Volumes for Nginx Configuration

Let's say you have a custom nginx.conf file that you want to use instead of the default one.

Step 1: Create your custom nginx.conf

Create a file named nginx.conf in your project directory. For example:

nginx
events {
    worker_connections  1024;
}

http {
    server {
        listen 80;
        server_name localhost;

        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
        }
    }
}

Step 2: Run the Nginx container with a volume

Now, let's run the official Nginx container and tell it to use our custom configuration file.

bash
docker run -d -p 8080:80 \
  -v $(pwd)/nginx.conf:/etc/nginx/nginx.conf:ro \
  nginx:latest

Let's break down that -v flag:

  • -v: This is the flag to mount a volume.
  • $(pwd)/nginx.conf: This is the path to your custom configuration file on your host machine. $(pwd) is a handy way to get the current working directory.
  • :/etc/nginx/nginx.conf: This is the path inside the container where the file will be mounted. We are overwriting the default Nginx configuration file.
  • :ro: This makes the volume read-only inside the container. This is a good practice for configuration files to prevent the container from accidentally modifying them.

Now, your Nginx container is running with your custom configuration! If you need to make changes, you can simply edit the nginx.conf file on your host and then restart the container for the changes to take effect.

bash
# First, find your container ID
docker ps

# Then, restart the container
docker restart <container_id>

This is a much faster and more efficient workflow than rebuilding the image for every configuration change.

Real-world Scenario: Imagine you're managing a fleet of Nginx containers for different websites. You can have a directory of configuration files on your host machine and launch a container for each website, each mounting its own specific configuration. This makes managing multiple sites a breeze!


3. Nginx as an API Gateway: Concepts and Practical Setup 🚪

The "What" and "Why"

What is an API Gateway?

An API Gateway is a server that acts as a single entry point for all of your backend services (APIs). Instead of clients having to know the addresses of all your different microservices, they just talk to the API gateway. The gateway then intelligently routes the requests to the appropriate service.

The Problem It Solves

In a modern microservices architecture, you might have dozens or even hundreds of small, independent services. Each service might have its own address and port. If a client application (like a mobile app or a single-page web app) had to know about and connect to all of these services, it would be a chaotic mess. It would be like a mail carrier having to know the exact desk location of every employee in a massive office building.

How Nginx as an API Gateway Solves It

Nginx is incredibly good at handling a massive number of concurrent connections and routing traffic based on rules. This makes it an excellent choice for an API Gateway. It can act as the "receptionist" for your backend services. All requests come to Nginx, and based on the request's path, Nginx decides which backend service should handle it.

This provides a single, stable entry point for your clients, simplifies client-side code, and allows you to add features like authentication, rate limiting, and caching at a single point.

Practical Setup: Nginx as a Simple API Gateway

Let's imagine we have two backend services:

  • A users-service running on localhost:3000
  • An orders-service running on localhost:4000

We want to use Nginx to route requests starting with /api/users to the users-service and requests starting with /api/orders to the orders-service.

Here's how our nginx.conf would look:

nginx
events {}

http {
    upstream users_service {
        server users-service:3000;
    }

    upstream orders_service {
        server orders-service:4000;
    }

    server {
        listen 80;

        location /api/users/ {
            proxy_pass http://users_service/;
        }

        location /api/orders/ {
            proxy_pass http://orders_service/;
        }
    }
}

Let's dissect this configuration:

  • upstream blocks: We define two groups of servers called upstreams. This is where we list the addresses of our backend services. We're using the service names (users-service and orders-service) which will be resolved by Docker's internal networking if they are running in the same Docker network.
  • location blocks: These are the routing rules.
    • The first location block says that any request whose path starts with /api/users/ should be passed to the users_service upstream.
    • The second location block does the same for /api/orders/ and the orders_service.
  • proxy_pass: This is the magic directive that forwards the request to the specified upstream.

To make this work with Docker, you would typically use Docker Compose to define and run your multi-container application (Nginx and your two services). This ensures they are all on the same network and can communicate with each other.

A Funny Exaggeration: Without an API gateway, your frontend developers would need a phonebook-sized document just to know which microservice to call for what. With an API gateway, they just have one number to call – Nginx's!


Further Reading & Resources

And that's a wrap! You've taken your first steps into the powerful combination of Nginx and Docker. Keep experimenting, keep building, and soon you'll be a container-wrangling, reverse-proxying expert! Happy coding! 🚀

Challenge

You are building a microservices-based e-commerce platform. Your task is to configure an Nginx server to act as an API Gateway using Docker. You need to create a Dockerfile to build the Nginx image and an nginx.conf file to handle the request routing.

Scenario:

  • You have two backend microservices: product_service (accessible at product_service:3001) and inventory_service (accessible at inventory_service:3002).
  • Incoming public traffic arrives at Nginx on port 80.

Requirements:

  1. Dockerfile:

    • Use the nginx:latest official image as the base.
    • Copy the nginx.conf file you will create into the correct directory for Nginx's default configuration inside the container.
  2. nginx.conf:

    • Define two upstream groups named products and inventory.
    • The products upstream should point to product_service:3001.
    • The inventory upstream should point to inventory_service:3002.
    • Configure the main server to listen on port 80.
    • Create a routing rule (location block) to forward all requests with a path starting with /api/v1/products/ to the products upstream group.
    • Create another routing rule to forward all requests with a path starting with /api/v1/inventory/ to the inventory upstream group.
    • For both routing rules, ensure you pass the Host and X-Real-IP headers to the upstream services.

Expected result

Your solution should consist of a complete Dockerfile and nginx.conf file that satisfy all the requirements. The code should correctly configure Nginx to act as an API gateway for the two specified microservices.

Correct Dockerfile:

dockerfile
# --- Dockerfile ---
# Specify the base Nginx image
FROM nginx:latest

# Copy the custom configuration file from the host to the container
COPY nginx.conf /etc/nginx/nginx.conf
  • FROM nginx:latest: Correctly specifies the official Nginx image as the foundation for the build.
  • COPY nginx.conf /etc/nginx/nginx.conf: Correctly copies the local configuration file to the default path Nginx uses for its main configuration inside the container.

Correct nginx.conf:

nginx
# --- nginx.conf ---
events { worker_connections 1024; }

http {
    upstream products {
        server product_service:3001;
    }

    upstream inventory {
        server inventory_service:3002;
    }

    server {
        listen 80;

        location /api/v1/products/ {
            proxy_pass http://products/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }

        location /api/v1/inventory/ {
            proxy_pass http://inventory/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
}
  • upstream blocks: The products and inventory upstreams are correctly defined with the specified service names and ports.
  • location blocks: The location directives accurately target the /api/v1/products/ and /api/v1/inventory/ paths.
  • proxy_pass: The proxy_pass directive correctly forwards requests to the corresponding HTTP upstream group.
  • proxy_set_header: The required Host and X-Real-IP headers are correctly passed along, which is crucial for logging and application logic on the backend services.
nginx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.