TExcelTAD
Home › Vite › Vite Docker & Static Hosting

Vite Docker & Static Hosting

A built Vite app is just static files, so the production container doesn't need Node.js at all. The standard pattern is a multi-stage Docker build: stage one uses Node to run vite build, stage two copies only dist/ into a tiny nginx image.

Why multi-stage?

Single stage (Node serving files) Multi-stage (Node → nginx)
Image ~ 1 GB with node_modules and source Image ~ 50 MB, only HTML/JS/CSS + nginx
Ships your source code and dev tooling Ships only the build output
Needs a Node web server process nginx is fast, battle-tested, handles caching and gzip

The Dockerfile

dockerfile
# syntax=docker/dockerfile:1

# ---------- stage 1: build ----------
FROM node:22-alpine AS build
WORKDIR /app

# install dependencies first, so this layer is cached until package files change
COPY package.json package-lock.json ./
RUN npm ci

# then copy the source and build
COPY . .
ARG VITE_API_URL=/api
ENV VITE_API_URL=$VITE_API_URL
RUN npm run build

# ---------- stage 2: serve ----------
FROM nginx:1.27-alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80

Key points:

  • npm ci installs exactly what package-lock.json says — reproducible builds.
  • Copying package*.json before the rest of the source lets Docker reuse the dependency layer when only your code changes.
  • VITE_* variables are baked in at build time (they're replaced in the bundle), so pass them as ARGs, not as runtime -e flags.
  • COPY --from=build takes only dist/ from the first stage; everything else is thrown away.

Note: This very course site uses the same pattern: a node:22-alpine build stage running npm run build, then nginx-unprivileged serving dist/ on port 8080 with a health check.

.dockerignore

Keep the build context small and avoid copying your local node_modules (built for your OS) into the image:

text
node_modules
dist
.git
*.log
.env*.local
Dockerfile
docker-compose.yml

nginx configuration

nginx
# nginx.conf
server {
    listen 80;
    server_name _;
    root /usr/share/nginx/html;
    index index.html;

    gzip on;
    gzip_types text/plain text/css application/javascript application/json image/svg+xml;

    # hashed build files: cache for a year
    location /assets/ {
        add_header Cache-Control "public, max-age=31536000, immutable";
        try_files $uri =404;
    }

    # optional: forward API calls to a backend container
    location /api/ {
        proxy_pass http://api:3000/;
    }

    # SPA fallback: unknown paths get index.html, which is never cached
    location / {
        add_header Cache-Control "no-cache";
        try_files $uri $uri/ /index.html;
    }
}

try_files $uri $uri/ /index.html; means: serve the file if it exists, else a directory index, else fall back to index.html so the client-side router can handle /courses/vite. The /api/ block does in production what server.proxy did in development.

The decision nginx makes for each request, simulated:

js · try it yourself
const files = new Set(['/index.html', '/assets/index-C3k9pQ2x.js', '/favicon.svg']);

function nginx(uri) {
  if (uri.startsWith('/api/')) return `proxy_pass -> http://api:3000${uri.slice(4)}`;
  if (uri.startsWith('/assets/')) {
    return files.has(uri) ? '200 (Cache-Control: immutable)' : '404';
  }
  if (files.has(uri)) return `200 ${uri} (no-cache)`;
  return '200 /index.html (SPA fallback, no-cache)';
}

for (const uri of ['/', '/courses/vite', '/assets/index-C3k9pQ2x.js', '/assets/old-123.js', '/api/courses']) {
  console.log(uri.padEnd(26), nginx(uri === '/' ? '/index.html' : uri));
}
/                          200 /index.html (no-cache)
/courses/vite              200 /index.html (SPA fallback, no-cache)
/assets/index-C3k9pQ2x.js  200 (Cache-Control: immutable)
/assets/old-123.js         404
/api/courses               proxy_pass -> http://api:3000/courses

Build and run

bash · try it yourself
docker build -t my-vite-app --build-arg VITE_API_URL=/api .
docker run --rm -d -p 8080:80 --name web my-vite-app
curl -sI http://localhost:8080/ | head -n 3
[+] Building 38.2s (14/14) FINISHED
 => [build 1/6] FROM docker.io/library/node:22-alpine
 => [build 3/6] COPY package.json package-lock.json ./
 => [build 4/6] RUN npm ci
 => [build 5/6] COPY . .
 => [build 6/6] RUN npm run build
 => [stage-1 2/3] COPY nginx.conf /etc/nginx/conf.d/default.conf
 => [stage-1 3/3] COPY --from=build /app/dist /usr/share/nginx/html
 => exporting to image
 => => naming to docker.io/library/my-vite-app
3f9c1e7a2b8d4c6e0a1f5b9d7e3c2a4f6b8d0e1c3a5f7b9d2e4c6a8f0b1d3e5f
HTTP/1.1 200 OK
Server: nginx/1.27.5
Content-Type: text/html
bash · try it yourself
docker images my-vite-app
REPOSITORY    TAG       IMAGE ID       CREATED          SIZE
my-vite-app   latest    5d2a8c4e9f1b   12 seconds ago   49.8MB

docker compose

yaml
# docker-compose.yml
services:
  web:
    build:
      context: .
      args:
        VITE_API_URL: /api
    ports:
      - "8080:80"
    depends_on:
      - api
    restart: unless-stopped
  api:
    image: my-api:latest
    expose:
      - "3000"

Run everything with docker compose up -d --build.

Runtime configuration

Because VITE_* values are compiled in, one image = one configuration. If you need to deploy the same image to staging and production with different settings, load config at runtime instead:

js
// public/config.json is replaced per environment (e.g. mounted as a volume)
const config = await fetch(`${import.meta.env.BASE_URL}config.json`).then((r) => r.json());

Other static hosts

You don't always need Docker. Any static host works with the same dist/ folder: Netlify, Vercel, Cloudflare Pages, GitHub Pages, Firebase Hosting, AWS S3 + CloudFront, Azure Static Web Apps. Remember the same three rules everywhere: correct base, SPA fallback, and immutable caching for /assets/.

Tip: Use the unprivileged nginx image (nginxinc/nginx-unprivileged) to run as a non-root user; it listens on port 8080 instead of 80.

Test yourself

What does the final stage of a typical Vite Docker image contain?

  1. Node.js, node_modules and source
  2. nginx plus the dist/ files
  3. Only package.json
  4. The Vite dev server

How should VITE_API_URL be provided to a Docker build?

  1. docker run -e VITE_API_URL=... at runtime
  2. As a build argument, because Vite inlines it at build time
  3. In nginx.conf
  4. It can't be used with Docker

What does try_files $uri $uri/ /index.html; achieve?

  1. Blocks unknown URLs
  2. Serves real files, otherwise falls back to index.html for client-side routing
  3. Caches index.html forever
  4. Redirects to HTTPS