CI/CD on Azure · Part 2 of 7
Containerization
Multi-stage Dockerfile, docker-compose for development with hot reload, Nginx configuration, and full local validation before touching Azure.
- Docker
- Docker Compose
- Nginx
Why containerize a static site?
It is a fair question. A static site is a folder of HTML, CSS and JavaScript files. Any web server can serve it. So why go through Docker?
The answer fits in two words: reproducibility and anticipation
Reproducibility?
Without a container, the behavior of the site depends on the environment running it: Nginx version, system configuration, environment variables present or missing on the machine. What works on a development workstation may behave differently on the staging server, and differently again in production (the now famous: “but it works on my machine!”).
With a container, we turn the problem around: the environment is what gets packaged into the image. The same image, validated locally, is the one that then runs on Azure Container Apps in staging. What is tested on my workstation is exactly what will be deployed to that remote environment.
(Production, for its part, deliberately breaks away from this container logic; I explain why in the previous article, section “Why three environments so different from one another”.)
Anticipation?
This static site is only a first version, Phase 0 of an application that will grow into a full platform with an API, a database, a driver dashboard and a payment system. All of these components will run in containers too.
Containerizing right now, even for something as simple as an Nginx serving static files, means laying the foundations of a cloud-native n-tier architecture from day one: each application component in its own container, independent, replaceable, individually scalable. The CI/CD pipeline we are going to build around this image will be reused and extended for the next phases, without starting from scratch.
It is one of the fundamental principles of DevOps: good infrastructure habits are formed at the start of a project, not once complexity has already made change expensive.
The multi-stage Dockerfile
A Dockerfile is a recipe file: it describes, step by step, how to build a Docker image. In our case, this recipe has three distinct phases, what is called a multi-stage build: a dev stage for local development with hot reload, an intermediate builder stage that compiles the site, and a runner stage that produces the deployment image.
The most telling analogy for a sysadmin: picture an RPM build. You need a full build environment to build the package: compilers, headers, development libraries. But the final package installed on production servers only contains the binaries and files needed at runtime, not the build tooling. Docker multi-stage works on the same principle, except that here we have an extra stage dedicated entirely to development comfort, which will never be deployed anywhere.
The file lives at docker/Dockerfile. Here is its full content, annotated stage by stage:
# =============================================================================
# Stage 1: dev
# Role: local development environment with hot reload
# The source code is never copied into the image: it is mounted as a volume
# from the host machine when the container starts (see docker-compose.yml)
# =============================================================================
FROM node:22-alpine AS dev
WORKDIR /app
EXPOSE 3000
CMD ["sh", "-c", "corepack enable && corepack prepare [email protected] --activate && pnpm install --frozen-lockfile && pnpm dev"]
# Note the absence of COPY and of a classic RUN pnpm install: everything happens
# in the CMD, when the container starts rather than when the image is built.
# This is deliberate (and detailed in the next section on docker-compose):
# this stage has no value outside of a bind mount of the source code.
# Building it alone, with no mounted volume, would start a container with
# an empty /app that would fail at pnpm install.
# =============================================================================
# Stage 2: builder
# Role: install the dependencies and compile the static site
# This intermediate image is completely discarded from the final image
# =============================================================================
FROM node:22.22-alpine AS builder
ENV CI=true
# CI=true is a convention honored by many JS tools (Next.js included):
# some interactive or auto-detection behaviors are disabled,
# to guarantee strictly identical behavior on every build.
WORKDIR /app
# Sets the working directory in the container.
# All the following commands run from /app.
COPY package.json pnpm-lock.yaml ./
# We first copy only the files that declare the dependencies.
# Why not copy everything at once? Docker cache optimization:
# if package.json has not changed, Docker reuses the cache of the next
# step (pnpm install) without running it again. A significant time saver.
RUN corepack enable && corepack prepare [email protected] --activate
# corepack is the package manager manager of Node.js.
# It lets us use pnpm at a pinned version, without installing it globally.
RUN pnpm install --frozen-lockfile --ignore-scripts
# Installs the dependencies declared in pnpm-lock.yaml.
# --frozen-lockfile: forbids any change to the lockfile during the install.
# Guarantees that the build is reproducible: we install exactly
# what the developer validated, not a more recent version.
# --ignore-scripts: runs no post-install script from third-party dependencies.
# Good security practice: a compromised package cannot run
# arbitrary code during the build.
COPY . .
# Now we copy the rest of the source code.
# Files listed in .dockerignore are automatically excluded.
RUN pnpm build
# Runs the Next.js compilation.
# Produces the out/ folder containing the whole static site.
# If the build fails (TypeScript error, missing import...),
# the Dockerfile stops here and the image is not created.
# =============================================================================
# Stage 3: runner
# Role: serve the static files with Nginx
# This is the image that will be deployed on Azure Container Apps
# =============================================================================
FROM nginx:1.30-alpine AS runner
# Official Nginx image, Alpine variant.
# It does not contain Node.js, on purpose.
# Base size: ~8 MB.
RUN rm -rf /usr/share/nginx/html/*
# Docker's "COPY" merges content into the target folder instead of replacing it.
# Nginx's default directory contains files that would not be replaced, so they would stay.
# Here, "50x.html". So we delete the whole content of the directory.
COPY --from=builder /app/out /usr/share/nginx/html
# We pick up only the out/ folder produced by the builder stage.
# Everything else (node_modules, source code, build tools) is left behind.
# --from=builder refers to the alias defined on the 2nd FROM.
COPY docker/nginx.conf /etc/nginx/conf.d/default.conf
# We overwrite the default Nginx configuration with ours.
# See the next section for the details of this configuration.
EXPOSE 80
# Exposes the container on port 80 when the container starts.
CMD ["nginx", "-g", "daemon off;"]
# Runs Nginx in the foreground (daemon off).
# Docker expects the main process to stay in the foreground.
# If it exits, the container stops. "daemon off" guarantees this behavior.An important point to keep in mind for what follows: only the runner stage is self-contained. The code is frozen into the image at build time (COPY . . in the builder stage, then the static files copied into runner), it needs no external source to work. It is the only one of the three stages that we push to a registry and deploy on Azure. The dev stage, on the contrary, intrinsically contains nothing: it depends entirely on a volume mounted at runtime, which makes it a strictly local stage.
docker-compose: orchestrating the dev stage
The dev stage of the Dockerfile, on its own, is not enough to start a working development environment: we still need to mount the source code as a volume, expose the right port, and pass a few environment variables. Rather than typing a long docker run command every time, this configuration is declared once and for all in a docker-compose.yml file, at the root of the project:
services:
app:
build:
context: .
dockerfile: docker/Dockerfile
target: dev
network: host
ports:
- '3000:3000'
volumes:
- .:/app
- /app/node_modules
- /app/.next
dns:
- 8.8.8.8
- 8.8.4.4
environment:
- WATCHPACK_POLLING=trueFor a sysadmin, docker-compose.yml is the equivalent of a slightly enriched systemd unit file: it declaratively describes how a service must be built and started, rather than documenting it as a command to copy and paste from a README. Nothing here is mandatory, everything could be translated into docker build + docker run with the right flags. But it is versioned and it boils down to a single command: docker compose up.
“target: dev”: building a single stage
target: devA useful reminder: our Dockerfile contains three stages (dev, builder, runner). Without further instruction, Docker would build the last stage of the file (runner) by default. target: dev forces Docker Compose to stop at the first stage (the one we care about here) without even trying to build the following stages.
Volumes: the point that deserves the most attention
volumes:
- .:/app # (1) bind mount
- /app/node_modules # (2) anonymous volume
- /app/.next # (3) anonymous volume(1) .:/app: the bind mount. The whole project directory, on the host machine, is mounted into /app inside the container. This is what makes hot reload possible: editing a src/... file on the machine makes it immediately visible in the container, as if the code lived there directly. It is the exact opposite of the runner stage logic, where the code is frozen into the image at build time.
(2) and (3): the anonymous volumes. Their role is more subtle: they mask the content of node_modules and .next that would otherwise come from the bind mount (1). Without these two lines, the host machine’s node_modules (often missing, or compiled for a system and architecture different from the container’s Alpine Linux) would overwrite the one installed inside the container, and vice versa.
Docker stacks volumes in the declared order: the .:/app bind mount first mounts the whole directory, then the anonymous volumes are mounted on top of it, precisely on these two sub-paths. This creates separate Docker volumes, managed only by the container, never synchronized with the host.
In practice:
node_modulesis installed inside the container (at startup, through theCMDof thedevstage) and stays binary-compatible with the container’s Alpine Linux, whatever the operating system of the host machine.next(the Next.js build cache) is isolated as well, which avoids conflicts between a cache generated on the host and a cache generated in the container
When a new dependency is added to the project, these anonymous volumes contain a stale version of node_modules. They then have to be destroyed explicitly to force a clean reinstall: docker compose down -v && docker compose up -d (the -v removes the anonymous volumes attached to the service).
“dns” and “environment”
dns:
- 8.8.8.8
- 8.8.4.4
environment:
- WATCHPACK_POLLING=trueThese two settings are workarounds for quirks of WSL2 (the Windows/Linux environment used to develop this project), not generic choices to reproduce as is on any machine:
dnsforces the container to use Google’s DNS resolvers rather than the sometimes temperamental ones automatically propagated by WSL2WATCHPACK_POLLING=trueforces Next.js to watch files by periodic polling rather than through nativeinotifyevents, because these filesystem events do not always cross a bind mount cleanly under WSL2
A boundary to keep in mind
The dev stage and its bind mount only make sense on the machine where the code is written. There is no “local disk” to mount on the Azure side: an Azure Container Apps container started from this stage would end up with an empty /app, and would crash immediately. That is precisely why only the runner stage (self-contained, code frozen into the image) is a candidate for remote deployment. The dev stage remains, by design, a strictly local tool.
The Nginx configuration
The default Nginx configuration is enough to serve simple static files, but it has a few gaps for a Next.js site in production. Here is our custom configuration:
# docker/nginx.conf
server {
listen 80;
server_name _;
# server_name _: accepts requests for any domain name.
# Behind Azure Container Apps, Azure manages the generated domain name
# and forwards requests to the container: this wildcard is appropriate.
root /usr/share/nginx/html;
# Root directory where Nginx looks for the files to serve.
# This is where we copied the content of out/.
index index.html;
# Client-side routing
location / {
try_files $uri $uri/ $uri.html /index.html;
# Next.js in static export generates .html files for each route.
# E.g.: /tours/ubud-culture-nature → out/tours/ubud-culture-nature.html
# try_files tries, in order:
# 1. The exact file ($uri)
# 2. A folder with an index ($uri/)
# 3. The matching .html file ($uri.html)
# 4. Fallback to index.html (for possible dynamic routes)
# Without this directive, Nginx would return 404 on direct URLs.
}
# Long-term cache for static assets
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ {
expires 1y;
add_header Cache-Control "public, immutable";
# Assets generated by Next.js have names with a content hash
# (e.g.: _next/static/chunks/main-abc123.js).
# A different hash = a different file = no cache problem.
# So we can cache aggressively for 1 year.
# "immutable" tells the browser never to revalidate.
}
# gzip compression
gzip on;
gzip_types text/plain text/css application/javascript application/json
image/svg+xml;
gzip_min_length 1024;
# Enables compression for text file types.
# Cuts network transfer size by 60 to 80% for JS/CSS.
# gzip_min_length: does not compress files under 1 KB
# (the CPU overhead is not worth it for small files).
# 404 error page
error_page 404 /404.html;
# Next.js automatically generates a 404.html file during the build.
}The .dockerignore
The .dockerignore works exactly like a .gitignore: it lists the files and folders to exclude when copying to the Docker build context. Without it, the COPY . . command in the Dockerfile would send the whole working directory to the Docker daemon, including large or sensitive files that have no business being in the image.
# Dependencies. Reinstalled in the container through pnpm install.
node_modules/
# Next.js build folder (dev). The prod build happens in the container.
.next/
# Previous static output. Generated in the container.
out/
# Environment files. Never include them in a Docker image
.env.local
.env*.local
# Project documentation, useless in the image.
*.md
# IDE configuration and local tools
.vscode/
# Git
.git/
.gitignore
# Docker itself, no need to include itself
Dockerfile*
docker-compose*.yml
.dockerignore
# System files
.DS_Store
Thumbs.dbThe benefits are twofold: performance (the build context sent to the daemon is smaller, hence faster) and security (we make sure that no sensitive file such as .env.local ends up in the image by accident).
Local build and test
Before pushing anything to Azure, we validate that the image builds and behaves correctly locally.
Building the image
docker build \
-f docker/Dockerfile \
--target runner \
--build-arg NEXT_PUBLIC_MAPBOX_TOKEN=the_token \
-t westbalidrivers:local \
.-f docker/Dockerfile: specifies the Dockerfile to use. It is the same file as the one used bydocker compose up, but here we target another stage--target runner: builds only therunnerstage (and itsbuilderprerequisite), completely ignoring thedevstage-t westbalidrivers:local: names and tags the image.: the build context is the current directory
The build takes a few minutes the first time (downloading the base images, installing the dependencies). Subsequent runs are almost instant thanks to the Docker cache, unless package.json has changed.
Checking the image size
docker images westbalidrivers:localIMAGE ID DISK USAGE CONTENT SIZE EXTRA
westbalidrivers:local eebfe3ebd8b1 98.9MB 27.3MB - Disk Usage: the space actually used on disk once the layers are decompressed and extracted into files, plus a share of metadata. The content represents the size of the image before decompression, which explains why disk usage is larger once inspected
- Content size: the size of the image layers as stored/transferred, that is compressed. This is what matters for a docker push/pull: the amount of data to transfer over the network.
Running the container and testing
docker run \
--rm \
-p 8080:80 \
--name westbalidrivers-test \
westbalidrivers:local--rm: removes the container automatically when it stops-p 8080:80: publishes the container’s port 80 on port 8080 of the host machine--name: gives the container a name to make the following commands easier
The site is now reachable at http://localhost:8080. Let’s check:
# Basic check: must return HTTP 200
curl -I http://localhost:8080
# Routing check: must return 200, not 404
curl -I http://localhost:8080/tours
# Cache header check on a static asset
curl -I http://localhost:8080/_next/static/chunks/main.js
# We should see: Cache-Control: public, immutable
# Content-Encoding: gzipInspecting the image content
# Open a shell in the container to check its content
docker run --rm -it --entrypoint sh westbalidrivers:local
# Inside the container:
ls /usr/share/nginx/html # must contain index.html, _next/, tours/, etc.
cat /etc/nginx/conf.d/default.conf # check that our config is in place
nginx -t # validate the syntax of the Nginx configurationChecklist before moving on
Before starting to configure Azure, make sure that:
-
docker buildcompletes without errors - The image is under 100 MB
-
http://localhost:8080returns HTTP 200 - The site routes (
/tours,/transfers,/gallery) return 200 -
Cache-Controlheaders are present on static assets -
nginx -treports no syntax error -
.env.localis not present in the image (can be checked through the shell in the container)
What we have achieved
At this point, a single Dockerfile gives us two distinct things:
- A local development environment (
devstage, orchestrated bydocker compose up), with hot reload and code mounted as a volume that will never leave the machine - A deployment image (
runnerstage) that:- Weighs less than 100 MB
- Only contains Nginx and static files. No build tool, no source code
- Is identical whatever the remote environment it will run in
- Handles routing, caching and compression correctly
This is the building block the whole pipeline will rest on. A clean image validated locally is the guarantee that the problems we run into from here on will be infrastructure problems, not application problems.
Next
In the next chapter, we will create our Azure Container Registry and push this image to it for the first time, by hand. This manual step matters: it validates the chain end to end before automating it with GitHub Actions.