Skip to content
Tutorials Center
My learning

Topics

Lesson 100 of 111 ยท Projects

Project: Serve a Static Site

Build and ship a static website with Docker: run nginx with a bind mount, add a custom config, bake everything into an image with a healthcheck, and use Compose.

Time to put the pieces together. In this project you will serve a small website with nginx, and take it through the three stages almost every Docker project goes through: first run it quickly with a bind mount while you develop, then configure it (custom 404 page, compression, cache headers, a health endpoint), and finally bake everything into your own image that anyone can run with one command and that Docker can monitor. At the end you will wrap it in Compose for a convenient daily workflow.

You need only Docker and a terminal. Every command and output below was run for real with Docker 29. Variable parts such as container IDs, dates and exact sizes are shortened or marked. Use any free local port; this walkthrough uses 18140 and binds it to 127.0.0.1, so the site is only reachable from your own machine (see Publishing Ports).

Step 1: Create the site

Make a project folder with a site directory inside it. The files are small on purpose.

TEXT
coffee/
  site/
    index.html
    about.html
    404.html
    style.css

site/index.html:

HTML
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Bean There Coffee</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>Bean There Coffee</h1>
  <p>Small-batch roasting, served from a container.</p>
  <p><a href="about.html">About us</a></p>
</body>
</html>

site/about.html:

HTML
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>About - Bean There Coffee</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>About us</h1>
  <p>We roast on Tuesdays and Fridays.</p>
  <p><a href="/">Home</a></p>
</body>
</html>

site/404.html:

HTML
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Page not found</title>
  <link rel="stylesheet" href="/style.css">
</head>
<body>
  <h1>404</h1>
  <p>This page does not exist. <a href="/">Back to the start</a>.</p>
</body>
</html>

site/style.css:

CSS
body { font-family: system-ui, sans-serif; max-width: 40rem; margin: 3rem auto; padding: 0 1rem; color: #2b1d12; }
h1 { color: #6f4e37; }
a { color: #a0522d; }

Step 2: Serve it with the stock nginx image

You do not need a Dockerfile for the first version. The official nginx image serves whatever is in /usr/share/nginx/html, so mount your folder there. Use :ro so the web server can never modify your source files. In a Bash shell on Linux or macOS the folder is "$PWD/site"; in Git Bash on Windows write "$(pwd -W)/site"; in PowerShell use ${PWD}\site.

CONSOLE
$ docker run -d --name coffee -p 127.0.0.1:18140:80 \
    -v "$PWD/site:/usr/share/nginx/html:ro" nginx:alpine
6fc136048af3

Let us break that command down using what you learned earlier: -d runs it in the background (Running Containers), -p 127.0.0.1:18140:80 publishes the container's port 80 on your loopback address only, and -v ...:ro is a read-only bind mount (Bind Mounts). Ask for the page:

CONSOLE
$ curl -i http://127.0.0.1:18140/
HTTP/1.1 200 OK
Server: nginx/1.31.8
Date: Fri, 23 Oct 2026 15:27:34 GMT
Content-Type: text/html
Content-Length: 373
Last-Modified: Fri, 23 Oct 2026 15:27:30 GMT
Connection: keep-alive
ETag: "6adb7ce2-175"
Accept-Ranges: bytes

<!doctype html>
<html lang="en">
...

Open the same address in your browser and you will see the page. Your terminal can also show the access log, which is the container's stdout (Logs and exec):

CONSOLE
$ curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:18140/missing
404
$ docker logs coffee 2>&1 | tail -2
2026/10/23 15:27:34 [error] 32#32: *2 open() "/usr/share/nginx/html/missing" failed (2: No such file or directory), client: 172.17.0.1, server: localhost, request: "GET /missing HTTP/1.1", host: "127.0.0.1:18140"
172.17.0.1 - - [23/Oct/2026:15:27:34 +0000] "GET /missing HTTP/1.1" 404 153 "-" "curl/8.22.0" "-"

Two things are already visible. The missing page returns the plain, built-in nginx 404 page (153 bytes), not ours. And the log line includes the client address 172.17.0.1, the bridge gateway, because the request came through Docker's port publishing.

Edit and refresh

The reason to start with a bind mount is the feedback loop. Change the text in site/index.html on your host, and the next request sees it, with no restart and no rebuild:

CONSOLE
$ sed -i 's|Small-batch roasting, served from a container.|Small-batch roasting. Now with a fresh edit!|' site/index.html
$ curl -s http://127.0.0.1:18140/ | grep -n "fresh"
11:  <p>Small-batch roasting. Now with a fresh edit!</p>

The read-only flag does its job from the other side. The server inside cannot write into the mounted folder:

CONSOLE
$ docker exec coffee sh -c 'touch /usr/share/nginx/html/x.txt'
touch: /usr/share/nginx/html/x.txt: Read-only file system
$ docker inspect --format '{{json .Mounts}}' coffee
[{"Type":"bind","Source":"<host path>","Destination":"/usr/share/nginx/html","Mode":"ro","RW":false,"Propagation":"rprivate"}]

On Docker Desktop with a project on a Windows or macOS drive, a bind mount goes through a file-sharing layer. For a handful of static files that is invisible. For thousands of files, or watch tools that rely on file-change events, it can be slower. See Bind Mounts.

Step 3: Configure nginx

The stock configuration has no custom 404 page, no compression for CSS, and says nothing about caching. To change it you replace the file /etc/nginx/conf.d/default.conf. First look at what the image ships, with comments removed:

CONSOLE
$ docker exec coffee cat /etc/nginx/conf.d/default.conf | grep -v '^\s*#' | grep -v '^$'
server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

Now write your own default.conf next to the site folder:

NGINX
server {
    listen 80;
    server_name _;

    root /usr/share/nginx/html;
    index index.html;

    server_tokens off;
    add_header X-Content-Type-Options "nosniff" always;

    gzip on;
    gzip_types text/css text/plain application/javascript;

    error_page 404 /404.html;

    location / {
        try_files $uri $uri/ =404;
    }

    location = /healthz {
        access_log off;
        default_type text/plain;
        return 200 "ok\n";
    }

    location ~* \.(css|js|svg|png|jpg|webp)$ {
        add_header Cache-Control "public, max-age=86400";
    }
}

What each part does:

  • server_tokens off hides the nginx version number in headers and error pages. It is a small hardening measure.
  • add_header X-Content-Type-Options "nosniff" always tells browsers not to guess content types. always adds it to error responses too.
  • gzip on compresses responses. HTML is always eligible; gzip_types adds CSS, plain text and JavaScript.
  • error_page 404 /404.html serves your page for missing files.
  • try_files $uri $uri/ =404 returns a file, a directory index or a 404; nothing else.
  • /healthz is a tiny endpoint that answers ok without touching the disk, which the healthcheck will use in a moment.
  • The last block sets a one-day browser cache for assets.

Always test a config before you use it. A throwaway container does that without touching your running site:

CONSOLE
$ docker run --rm -v "$PWD/default.conf:/etc/nginx/conf.d/default.conf:ro" nginx:alpine nginx -t
...
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

(The lines in between come from the image's start-up scripts. One of them says can not modify /etc/nginx/conf.d/default.conf (read-only file system?): it is the script that tries to enable IPv6 and it harmlessly gives up on a read-only mount.) Replace the first container with one that also mounts the config:

CONSOLE
$ docker rm -f coffee
$ docker run -d --name coffee -p 127.0.0.1:18140:80 \
    -v "$PWD/site:/usr/share/nginx/html:ro" \
    -v "$PWD/default.conf:/etc/nginx/conf.d/default.conf:ro" nginx:alpine

Check each feature:

CONSOLE
$ curl -i http://127.0.0.1:18140/missing
HTTP/1.1 404 Not Found
Server: nginx
Content-Type: text/html
Content-Length: 257
Connection: keep-alive
ETag: "6adb7ce2-101"
X-Content-Type-Options: nosniff

<!doctype html>
<html lang="en">
...
  <h1>404</h1>
  <p>This page does not exist. <a href="/">Back to the start</a>.</p>
...
$ curl -s http://127.0.0.1:18140/healthz
ok
$ curl -s -i http://127.0.0.1:18140/style.css | grep -iE "^(HTTP|cache|x-content)"
HTTP/1.1 200 OK
Cache-Control: public, max-age=86400

The Server header no longer shows a version, the custom 404 page appears, the health endpoint answers. But look at the last result: X-Content-Type-Options is missing on style.css. This is one of nginx's best-known surprises. add_header directives are inherited from the outer level only if the inner block defines none of its own. The location that adds Cache-Control replaces the server-level headers instead of adding to them. The fix is to repeat the header there:

NGINX
    location ~* \.(css|js|svg|png|jpg|webp)$ {
        add_header Cache-Control "public, max-age=86400";
        add_header X-Content-Type-Options "nosniff" always;
    }

Config files mounted from the host are read when nginx starts, so restart the container (or run docker exec coffee nginx -s reload) and check again:

CONSOLE
$ docker restart coffee
coffee
$ curl -s -i http://127.0.0.1:18140/style.css | grep -iE "^(HTTP|cache|x-content)"
HTTP/1.1 200 OK
Cache-Control: public, max-age=86400
X-Content-Type-Options: nosniff
$ curl -s -D - -o /dev/null -H 'Accept-Encoding: gzip' http://127.0.0.1:18140/ | grep -i content-encoding
Content-Encoding: gzip

Compression works when the client asks for it. This is the loop you will repeat in every project: change the config, test it, look at the real response. Finding a problem like the missing header is exactly why you check headers with curl -i rather than trusting the config.

Step 4: Bake it into an image

Bind mounts are perfect for development, but to ship the site you want one artifact that contains everything: a Docker image. Whoever runs it needs neither your folder nor your config. Create a build folder (here ctx) containing site/, default.conf and a Dockerfile:

DOCKERFILE
FROM nginx:1.31-alpine

COPY default.conf /etc/nginx/conf.d/default.conf
COPY site/ /usr/share/nginx/html/

EXPOSE 80

HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
  CMD wget -q --spider http://127.0.0.1/healthz || exit 1

Read it as a recipe (Writing a Dockerfile):

  1. Start from a pinned minor version of the Alpine-based nginx image. It stays predictable, but still receives patch updates when you rebuild (Tags and Registries).
  2. Copy the config and the site into the places nginx reads them from. COPY is the right instruction for local files (COPY and ADD). The config is copied first because it changes less often than the content, which keeps rebuilds fast in practice (The Build Cache).
  3. EXPOSE 80 documents the port; it does not publish it (WORKDIR, USER, EXPOSE and LABEL).
  4. The healthcheck asks the /healthz endpoint from inside the container, using wget, which Alpine's BusyBox provides. --start-period gives nginx a few seconds before failures count (HEALTHCHECK).

Add a .dockerignore so that build files do not end up in the context (Build Context and .dockerignore):

TEXT
Dockerfile
.dockerignore
*.md
.git

Build and look at the result:

CONSOLE
$ docker build -t coffee:1.0.0 .
...
#8 naming to docker.io/library/coffee:1.0.0 done
#8 DONE 1.4s
$ docker images coffee:1.0.0 --format '{{.Repository}}:{{.Tag}} {{.Size}}'
coffee:1.0.0 93.7MB
$ docker history coffee:1.0.0 --format 'table {{.CreatedBy}}\t{{.Size}}' | head -5
CREATED BY                                      SIZE
HEALTHCHECK {Test:[CMD-SHELL wget -q --spidโ€ฆ   0B
EXPOSE [80/tcp]                                 0B
COPY site/ /usr/share/nginx/html/ # buildkit    36.9kB
COPY default.conf /etc/nginx/conf.d/default.โ€ฆ   20.5kB

(Sizes are as reported on this machine, and differ with the platform and Docker's image store.) Your two COPY layers are a few kilobytes; almost the entire image is the nginx base. That is the nice property of static sites: the content is tiny compared to the server.

Step 5: Run it and watch the healthcheck

Now run the image without any mounts:

CONSOLE
$ docker run -d --name coffee -p 127.0.0.1:18140:80 --restart unless-stopped coffee:1.0.0
$ docker ps --filter name=coffee --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}'
NAMES    IMAGE          STATUS                           PORTS
coffee   coffee:1.0.0   Up 1 second (health: starting)   127.0.0.1:18140->80/tcp

Wait about ten seconds and ask again:

CONSOLE
$ docker ps --filter name=coffee --format 'table {{.Names}}\t{{.Status}}'
NAMES    STATUS
coffee   Up 14 seconds (healthy)
$ curl -s http://127.0.0.1:18140/healthz
ok
$ curl -s -o /dev/null -w "%{http_code} %{content_type}\n" http://127.0.0.1:18140/about.html
200 text/html
$ curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:18140/nope
404

The status moves from health: starting to healthy after the first successful check. If the check starts failing (say a bad config is reloaded), Docker marks the container unhealthy. This is what that looks like when the server config is deleted and reloaded inside a test container, with the interval shortened to two seconds:

CONSOLE
$ docker exec coffee-test rm /etc/nginx/conf.d/default.conf
$ docker exec coffee-test nginx -s reload
$ docker ps --filter name=coffee-test --format '{{.Status}}'
Up 13 seconds (unhealthy)

Docker itself does not restart an unhealthy container; orchestrators and monitoring tools react to the status. --restart unless-stopped restarts the container only when it exits or the daemon restarts. That difference is explained in The Container Lifecycle.

A hardened run (optional)

A static web server has no reason to write to its own filesystem except for a few runtime folders. Make the root filesystem read-only and give nginx small in-memory directories for those (seccomp, AppArmor and Read-Only Filesystems):

CONSOLE
$ docker run -d --name coffee -p 127.0.0.1:18140:80 --read-only \
    --tmpfs /var/cache/nginx --tmpfs /run --tmpfs /tmp coffee:1.0.0
$ curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:18140/
200

It starts and serves correctly. If nginx wants to write somewhere else for a feature you enable later, it fails with "Read-only file system" and the message tells you which folder needs a tmpfs.

Step 6: Wrap it in Compose

Typing long docker run commands every day is tiring. Put the runtime settings into compose.yaml next to the Dockerfile:

YAML
services:
  web:
    build: .
    image: coffee:1.0.0
    ports:
      - "127.0.0.1:18140:80"
    restart: unless-stopped

And a second file, compose.override.yaml, which Compose merges automatically on your development machine. It bind-mounts the site and config so edits show up instantly, as in steps 2 and 3:

YAML
services:
  web:
    volumes:
      - ./site:/usr/share/nginx/html:ro
      - ./default.conf:/etc/nginx/conf.d/default.conf:ro

(See Compose for Development and Multiple Files, Profiles and Extends for why this pattern works.) Start the stack:

CONSOLE
$ docker compose up -d --build
 Network coffee_default Created
 Container coffee-web-1 Creating
 Container coffee-web-1 Created
 Container coffee-web-1 Starting
 Container coffee-web-1 Started
$ docker compose ps --format 'table {{.Service}}\t{{.Status}}\t{{.Ports}}'
SERVICE   STATUS                   PORTS
web       Up 9 seconds (healthy)   127.0.0.1:18140->80/tcp

The healthcheck came from the image, so Compose shows healthy without any extra configuration. Edit about.html and the change appears on the next request, thanks to the override file:

CONSOLE
$ sed -i 's|We roast on Tuesdays and Fridays.|We roast on Tuesdays, Thursdays and Fridays.|' site/about.html
$ curl -s http://127.0.0.1:18140/about.html | grep roast
  <p>We roast on Tuesdays, Thursdays and Fridays.</p>

In production you run docker compose -f compose.yaml up -d, which ignores the override and serves the content baked into the image.

Step 7: Clean up

Terminal
docker compose down
docker rm -f coffee
docker rmi coffee:1.0.0

Only remove images and containers you created. See Cleaning Up for safe ways to find leftovers.

What you practised

This small project used most of the first half of the track: pulling an image, running and publishing ports, bind mounts (including read-only), reading logs, writing a Dockerfile with a healthcheck, the build context, tagging, read-only root filesystems, and Compose with an override file. The same shape, "develop with mounts, ship with an image", appears again in the next projects, with databases and workers added. Next, a Node.js API with a Postgres database.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the development setup mount the site folder with :ro?

    A read-only bind mount means any write from inside, such as touch, fails with Read-only file system. That protects the files on your host.
  2. 2. In the nginx configuration, why was X-Content-Type-Options missing on style.css although it was set at the server level?

    nginx inherits add_header from the outer level only when the inner block has none. The asset location had Cache-Control, so it replaced the server-level headers.
  3. 3. You edit default.conf, which is bind-mounted into a running nginx container. What is needed for nginx to use the change?

    The mounted file changes immediately, but nginx loads its configuration only at start and on reload.
  4. 4. What does the docker ps status (health: starting) tell you right after docker run?

    A container with a HEALTHCHECK begins as starting and turns healthy or unhealthy depending on check results, after the start period and retries.
  5. 5. Why is the image built in step 4 only a few kilobytes larger than the nginx base image?

    The two COPY layers hold a few small files (tens of kilobytes). The nginx and Alpine layers account for almost everything.

Summary

  • Develop with the stock nginx image and a read-only bind mount of your site folder; edits show up immediately without a rebuild.
  • Test configuration changes with nginx -t in a throwaway container, and verify real behavior with curl -i; watch for nginx's add_header inheritance rule.
  • A small Dockerfile (FROM, COPY of config and content, HEALTHCHECK) turns the site into a self-contained, versioned image; a .dockerignore keeps the context clean.
  • docker ps shows health: starting, then healthy or unhealthy; --restart and health are different mechanisms.
  • A read-only root filesystem with tmpfs for the runtime folders hardens a static server at no cost.
  • Compose plus compose.override.yaml gives one-command development (with mounts) and production (image only).

Next: Project: A Node.js API with a Database