Deployn

Astro.js & Docker: Deploy Your Site on a VPS (Static & Dynamic)

Astro.js with Docker on your VPS: static (Nginx) or dynamic (Node.js). Full tutorial with current Dockerfiles, Docker Compose, and deployment workflow.

Astro.js & Docker: Deploy Your Site on a VPS (Static & Dynamic) hero image
Contents
Tested with
Astro 7.4@astrojs/node 11.1Node.js 26 (node:lts)Nginx 1.31Caddy 2.11Docker 29.9Ubuntu 24.04
Last checked on

Want to build a modern, fast website with Astro.js and deploy it on your own server? Docker is the right tool for the job — by now, 92% of the IT industry relies on containers (Docker State of App Dev Report, 2025). In this post, I’ll walk you through the entire process: from the development environment to the live deployment of your Astro application using Docker and Docker Compose on a VPS.

Key Takeaways at a Glance

  • Astro grew from 29 domains (2021) to over 38,800 (2025), a 1,340× increase (TechnologyChecker.io, 2025).
  • Static builds via Nginx: lean (~94 MB image), extremely fast.
  • Dynamic builds via Node.js adapter: flexible, required for SSR routes.
  • Multi-stage Dockerfiles keep production images small and secure.
  • Docker Compose orchestrates the startup with a single command.

How to Prepare Your Development Environment

Three tools form the foundation for Astro and Docker development.

  1. Text Editor: Visual Studio Code (VS Code) is free and offers a huge extension library. The Astro extension for VS Code brings syntax highlighting and IntelliSense.

  2. Node.js: Astro is built on Node.js. Instead of a direct installation, I recommend using a version manager to switch flexibly between versions.

    • Windows: nvm-windows avoids permission issues.
    • Linux/macOS: The original nvm (Node Version Manager) can be installed via a curl or wget script.
    • Astro 7 requires Node.js 22.23.4 or newer. The LTS version meets that.
    Terminalbash
    nvm install lts # Install the latest LTS version
    nvm use lts     # Activate the LTS version
  3. Git: Essential for version control and easily transferring code to the server. Download Git.

    Terminalbash
    # During installation on Windows: choose VS Code as the default editor
    # Set the Default Branch Name to "main"

Open your terminal (in VS Code: Ctrl+Shift+`) and verify the installations:

Terminalbash
node -v
npm -v
git --version
nvm version

How to Create Your First Astro Project

Navigate to your project folder and launch the Astro CLI. The framework generates the basic files and installs all dependencies automatically.

Terminalbash
# Create project with minimal template
npm create astro@latest -- --template minimal my-astro-project

# Change into the project directory
cd my-astro-project

# Install dependencies (often already done during creation)
npm install
# or pnpm install

# Start the development server
npm run dev
# or pnpm dev

By default, you’ll find the Astro default page at http://localhost:4321.

Changes in src/pages/index.astro are immediately visible via Hot Module Replacement.

Understanding Astro: Pages, Layouts, and Components

Astro projects follow a clear structure. Once you understand it, you can build projects of any size.

  • src/pages/: Every .astro file here becomes a route. index.astro becomes /, about.astro becomes /about.
  • src/layouts/: Reusable page structures. A typical layout (BaseLayout.astro) contains the HTML skeleton with a <slot /> that each using page fills.
  • src/components/: Reusable UI elements like headers, footers, or cards. Importable in pages and layouts.
  • Styling: Global CSS files are imported in layouts. Within an .astro file, <style> tags are scoped by default, meaning they only apply to the respective component.
astro
---
// Example: src/layouts/BaseLayout.astro
import Header from "../components/Header.astro";
import Footer from "../components/Footer.astro";
import "../styles/global.css";

interface Props {
	title: string;
	description?: string;
}

const { title, description = "My Astro Site" } = Astro.props;
---

<!doctype html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<meta name="description" content={description} />
		<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
		<title>{title} | Astro Demo</title>
	</head>
	<body>
		<Header />
		<main class="container">
			<slot />
		</main>
		<Footer />
	</body>
</html>

<style>
	.container {
		max-width: 1100px;
		margin-left: auto;
		margin-right: auto;
		padding-left: 1rem;
		padding-right: 1rem;
		flex-grow: 1;
	}
	body {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
	}
</style>

Static or Dynamic: Which Build Is Right for You?

Nginx serves static files under load approximately 4,874 times faster than a Node.js server, with a median response time of 0.05 ms compared to 253 ms (Benchmark, Adam Jones, 2024). For pure delivery, the Nginx approach is clearly superior. However, not every project can get by with static files alone.

I didn’t want to just quote numbers, so I measured myself. On a Hetzner server (2 vCPUs, 4 GB RAM), each variant ran in a container, and I sent 20,000 requests to each with ab -n 20000 -c 50 -k. The measuring tool ran on the same machine and takes some CPU time from the server, so the absolute values are lower than they would be with a measurement from outside. The ratio stays meaningful:

Variant Requests per second Time per request RAM after the test
Nginx, static site 15,150 to 15,880 (2 runs) 3.1 to 3.3 ms 8 MiB
Node.js, prerendered page 5,871 8.5 ms -
Node.js, SSR route 1,838 27.2 ms 153 MiB

Even for a prerendered page, Nginx serves about 2.7 times as fast as the Node server, and an SSR route takes about 8.6 times as long. SSR only costs CPU time where the page really has to be dynamic.

The Static Build (Default)

This is the standard in Astro. npm run build generates pure HTML, CSS, and JavaScript in the dist/ folder. No Node.js server is needed at runtime.

Terminalbash
npm run build

You can deploy the dist/ folder on any static web host.

Dynamic Routes with the Node Adapter

Does a page need dynamic data that changes with every request (e.g., user info from request headers)? That’s where Server-Side Rendering (SSR) comes in.

  1. Install the adapter:

    Terminalbash
    npx astro add node

    This adjusts your astro.config.mjs and installs the necessary packages.

  2. Disable prerendering: Explicitly turn it off for the dynamic page:

    astro
    ---
    // src/pages/request-info.astro
    export const prerender = false;
    
    const userAgent = Astro.request.headers.get("user-agent") || "Unknown";
    
    import BaseLayout from "../layouts/BaseLayout.astro";
    ---
    
    <BaseLayout title="Request Info">
    	<h1>Your Request Info</h1>
    	<p>Your User-Agent: {userAgent}</p>
    </BaseLayout>
  3. Build result: The dist/ folder now contains not only static assets (client/) but also server code (server/entry.mjs) that must be executed with Node.js at runtime.

Docker as the Foundation of Your Deployment

Docker packages your application along with all its dependencies into an isolated container. The result: your app runs in the same environment, locally and on the server. Docker reports a 92% adoption rate in the IT industry in 2025, an increase of 12 percentage points over the previous year (Docker State of App Dev Report, 2025). It’s also very popular in the self-hosting community for several reasons. Containerization is not a niche topic — it’s the standard.

The .dockerignore: What Doesn’t Belong in the Image

Similar to .gitignore, this file tells Docker which files should not be copied. This speeds up the build and keeps the image small.

# .dockerignore
.DS_Store
node_modules
npm-debug.log
dist
.astro
.env*
*.env
.git
.vscode
Dockerfile*
docker-compose*
compose*
README.md

How to Containerize a Static Astro Site

For purely static sites, I use a two-stage Docker build. The build stage generates the files with Node.js, and the runtime stage serves them with Nginx. This follows the official Astro Docker recipe.

Dockerfile (static site):

Dockerfiledockerfile
# ---- Build Stage ----
FROM node:lts-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# ---- Runtime Stage ----
FROM nginx:alpine AS runtime
COPY ./nginx/nginx.conf /etc/nginx/nginx.conf
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
  • node:lts-alpine is the slim variant of the Node image. It is enough to build the site, and the download is much smaller.
  • npm ci installs exactly the versions from package-lock.json and aborts if the lockfile and package.json don’t match. A build then gives the same result on every machine. If you use pnpm, replace the lines with corepack enable and pnpm install --frozen-lockfile.
  • Only the runtime stage ends up in the final image. Node.js and node_modules stay behind in the build stage.

src/pages/404.astro:

For Nginx to answer unknown URLs properly, the site needs its own 404 page. Astro turns it into the file 404.html.

src/pages/404.astroastro
---
import BaseLayout from "../layouts/BaseLayout.astro";
---

<BaseLayout title="Page not found">
	<h1>404: Page not found</h1>
	<p><a href="/">Back to the home page</a></p>
</BaseLayout>

nginx/nginx.conf:

Put the configuration file in the nginx/ folder in your project root. It enables Gzip, sets cache headers for files with a hash in their name, and blocks hidden files.

nginx/nginx.confnginx
worker_processes auto;

events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

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

        gzip on;
        gzip_vary on;
        gzip_proxied any;
        gzip_comp_level 6;
        gzip_min_length 1000;
        gzip_types text/plain text/css text/xml application/json
                   application/javascript application/xml+rss
                   application/atom+xml image/svg+xml;

        # Astro adds hashes to files in /_astro/, so they can be cached forever
        location /_astro/ {
            add_header Cache-Control "public, max-age=31536000, immutable";
            access_log off;
        }

        location ~ /\. {
            deny all;
        }

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

        error_page 404 /404.html;
    }
}

Three decisions in this file:

  • try_files $uri $uri/ =404: This used to fall back to index.html. That suits single-page apps, but not a static Astro site: every wrong URL then returns the home page with status 200, and broken links go unnoticed. Now Nginx answers with a real 404 and shows your 404.html.
  • Cache only for /_astro/: Astro adds a hash to these files. When the content changes, the name changes, so the browser may keep them for a year. Everything else (HTML, favicon) is checked on every visit.
  • worker_processes auto: Inside the container, Nginx sees all CPU cores of the host. auto starts one worker per core, which makes a noticeable difference under load.

On my test server, the finished image is 94 MB.

How to Containerize a Dynamic Astro Site

With the Node adapter, you don’t need Nginx. The Dockerfile follows the multi-stage pattern from the Astro docs, which separates production dependencies from build dependencies. That speeds up later builds when only the source code has changed.

Dockerfile (dynamic site with Node.js):

Dockerfiledockerfile
# ---- Base Stage ----
FROM node:lts-alpine AS base
WORKDIR /app
COPY package.json package-lock.json ./

# ---- Production Dependencies ----
FROM base AS prod-deps
RUN npm ci --omit=dev

# ---- Build Dependencies + Build ----
FROM base AS build-deps
RUN npm ci

FROM build-deps AS build
COPY . .
RUN npm run build

# ---- Runtime Stage ----
FROM base AS runtime
COPY --from=prod-deps /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
ENV HOST=0.0.0.0
ENV PORT=4321
EXPOSE 4321
USER node
CMD ["node", "./dist/server/entry.mjs"]
  • Cache: If only your source code changes and package.json doesn’t, Docker skips the two npm ci steps and goes straight to the build. On large projects that saves minutes.
  • HOST=0.0.0.0: Without this line, the server only listens on localhost inside the container, and nothing arrives from outside.
  • USER node: The server does not run as root. The node:lts-alpine image already ships the node user. Inside the container, id then shows uid=1000(node).
  • Size: With node:lts-alpine, the image is 443 MB. The same Dockerfile with node:lts (Debian) comes to 1.97 GB. A large part of the 443 MB is node_modules, because Astro itself is needed at runtime.

Docker Compose: Orchestrating Containers

docker compose makes starting and configuring containers much easier. It’s worth it even for a single container.

compose.yml:

compose.ymlyaml
services:
    astro-app:
        build:
            context: .
            dockerfile: Dockerfile
        container_name: mein-astro-container
        ports:
            # Static site (Nginx on port 80 in the container)
            - "80:80"
            # Dynamic site (Node.js on port 4321 in the container)
            # - "80:4321"
        restart: unless-stopped
        healthcheck:
            # For the dynamic site: http://127.0.0.1:4321/
            test: ["CMD", "wget", "-q", "--spider", "http://127.0.0.1/"]
            interval: 30s
            timeout: 5s
            retries: 3
  • File name: compose.yml, compose.yaml or docker-compose.yml all work, Docker Compose v2 recognizes every variant.
  • ports: Pick the right mapping: 80:80 for Nginx, 80:4321 for the Node adapter. The left number is the port on the server that you open in the browser.
  • healthcheck: Docker requests the page every 30 seconds and shows the state healthy or unhealthy in docker compose ps. alpine already includes wget, so there is nothing to install.
  • The image: line: I leave it out. Compose then names the image after the project, and you don’t have a latest tag in play.

How to Deploy Your Astro App to a VPS

Now we put it all together. I played through every step on a server running Ubuntu 24.04, once with the static and once with the dynamic variant. You need:

  • a VPS running Ubuntu 24.04 or another Docker-compatible system. If you don’t have one yet, my VPS guide for beginners helps with choosing and securing one. With the Cloud-Init configurator, you can have a Hetzner server set up with Docker and your SSH key right when you create it, which saves you the installation in step 1.
  • a Git repository with your project, for example on GitHub.
  • optionally a domain, if you want to serve the site over HTTPS.

The process at a glance:

  1. Install Docker on the server
  2. Get the code onto the server
  3. Build and start the container
  4. Check the status and open the site
  5. Mind the firewall
  6. Domain and HTTPS with Caddy
  7. Roll out updates

If the terminal commands are still unfamiliar, my Linux terminal guide helps.

1. Install Docker on the server

Connect to your server via SSH:

Terminalbash
ssh root@{{server_ip}}

Then install Docker including the Compose plugin. These commands apply to Ubuntu:

Terminalbash
sudo apt-get update
sudo apt-get install -y ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc

echo \
 "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
 $(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}") stable" | \
 sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update
sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin git

Afterwards, check that everything is there:

Terminalbash
docker --version
docker compose version
Docker version 29.9.3, build 5457199
Docker Compose version v5.7.0

Compose support is already included as a plugin, and you call it with docker compose (without a hyphen). A more detailed server setup with Docker is in my post on the Ubuntu home server.

2. Get the code onto the server

Clone your repository, which you pushed beforehand:

Terminalbash
git clone YOUR_REPOSITORY_URL mein-astro-projekt
cd mein-astro-projekt

If the repository is private, the server needs access: either a deploy key or an access token for the HTTPS URL. If you don’t know Git yet, my Git tutorial explains the basics.

You can also work without Git and copy the project folder from your computer. rsync only transfers what has changed:

Terminalbash
rsync -az --exclude node_modules --exclude dist --exclude .astro --exclude .git \
  ./ root@{{server_ip}}:/root/mein-astro-projekt/

3. Build and start the container

In the project folder on the server:

Terminalbash
sudo docker compose up --build -d

docker compose up starts the services from the compose.yml. --build forces the image to be rebuilt in case the code or Dockerfile changed. -d starts everything in the background. The first build takes a while because Docker has to download the base images. On the server, 13 seconds passed between the command and the running container for me.

4. Check the status and open the site

Right after the start, docker compose ps shows the state health: starting. After the first successful health check, so after about 30 seconds, it shows healthy:

Terminalbash
sudo docker compose ps
NAME                   IMAGE                          COMMAND                  SERVICE     CREATED          STATUS                    PORTS
mein-astro-container   mein-astro-projekt-astro-app   "/docker-entrypoint.…"   astro-app   35 seconds ago   Up 35 seconds (healthy)   0.0.0.0:80->80/tcp, [::]:80->80/tcp

You check whether the server responds directly on the server with curl:

Terminalbash
curl -I http://localhost
HTTP/1.1 200 OK
Server: nginx/1.31.8
Content-Type: text/html

Now open http://SERVER-IP in your browser. Your Astro website is live.

The static Astro site in the browser, served by Nginx in the container

If the container doesn’t run, the logs show the cause:

Terminalbash
sudo docker compose logs -f astro-app

5. Firewall: Docker bypasses ufw

If you use the ufw firewall on the server, Docker has a surprise in store. I enabled ufw and allowed only port 22. The container was still reachable from outside. Docker writes published ports directly into the kernel’s firewall rules, and ufw doesn’t see these rules.

Two things help:

  • Publish ports that shouldn’t be public only locally: "127.0.0.1:8080:80" instead of "8080:80".
  • Also use your provider’s cloud firewall. It sits in front of the server, and Docker can’t bypass it. More on securing a server is in the VPS guide.

6. Domain and HTTPS with Caddy

A site at http://SERVER-IP is fine for a test. For real visitors, you need a domain and HTTPS. I use Caddy as a reverse proxy for that: it gets the certificate from Let’s Encrypt on its own and renews it automatically.

  1. At your domain provider, create an A record for astro.yourdomain.com that points to SERVER-IP. Wait until name resolution works.
  2. Extend the compose.yml. The Astro app no longer publishes a port, only Caddy is reachable from outside:
compose.ymlyaml
services:
    astro-app:
        build:
            context: .
            dockerfile: Dockerfile
        container_name: mein-astro-container
        ports:
            - "80:80"
        restart: unless-stopped
        healthcheck:
            test: ["CMD", "wget", "-q", "--spider", "http://127.0.0.1/"]
            interval: 30s
            timeout: 5s
            retries: 3

    caddy:
        image: caddy:2
        container_name: caddy
        restart: unless-stopped
        ports:
            - "80:80"
            - "443:443"
            - "443:443/udp"
        volumes:
            - ./Caddyfile:/etc/caddy/Caddyfile:ro
            - caddy_data:/data
            - caddy_config:/config
        depends_on:
            - astro-app

volumes:
    caddy_data:
    caddy_config:
  1. Put the Caddyfile next to the compose.yml. For the static site, it points to port 80 of the container, for the dynamic site to 4321:
Caddyfilecaddy
{{domain}} {
    reverse_proxy astro-app:80
}

Here, astro-app is the service name from the compose.yml. Compose services in the same project reach each other by this name. If you prefer to click your setup together in a form, the Caddyfile generator helps. If you’d rather use Traefik than Caddy, you’ll find it in my guide to Traefik as a reverse proxy.

  1. Start everything again:
Terminalbash
sudo docker compose up -d

Caddy gets the certificate on the first request. For me it was ready after about five seconds. The log shows the line certificate obtained successfully. Check both addresses:

Terminalbash
curl -I https://{{domain}}
curl -I http://{{domain}}
HTTP/2 200
...
HTTP/1.1 308 Permanent Redirect
Location: https://{{domain}}/

So Caddy redirects HTTP to HTTPS on its own. This is what the dynamic site looks like when you open /request-info:

The dynamic page shows the browser’s user agent, served by the Node server behind Caddy

7. Roll out updates

If you made changes locally, the update always works the same way:

  1. Commit and push the code
  2. On the server, fetch the new state and rebuild:
Terminalbash
cd mein-astro-projekt
git pull
sudo docker compose up --build -d
  1. Remove old image layers so the server doesn’t fill up:
Terminalbash
sudo docker image prune -f

Docker builds the new image and replaces the container. For the dynamic site, unchanged npm ci steps can be reused from the cache, so the update is faster.

If an update went wrong, switch to the last working commit on the server and rebuild: git log --oneline shows you the states, git checkout COMMIT_ID resets the code, then run sudo docker compose up --build -d again. With git checkout main, you return to the current state later.

When something doesn’t work

  • Bind for :::80 failed: port is already allocated: Another container or service already uses port 80. sudo docker ps shows which one. Stop it or choose a different host port for the Astro app, for example "8080:80".
  • 502 from Caddy: The proxy can’t reach the container. Check that the port in the Caddyfile matches the container (80 for Nginx, 4321 for Node.js) and that you restarted Caddy after a change.
  • [NoAdapterInstalled] during the build: A page sets prerender = false, but the Node adapter is missing. Install it with npx astro add node and commit the changed astro.config.mjs along with package.json and the lockfile.
  • Container doesn’t start or keeps restarting: The cause is almost always in sudo docker compose logs astro-app.

Frequently asked questions

Can I deploy Astro without Docker?

Yes. Astro generates static files that can be hosted on any web server. With the Node.js adapter, Astro also produces a server that runs on any machine with Node.js. Docker makes both reproducible and lets you start them with a single command.

When do I need server-side rendering?

SSR is needed when pages require fresh data on every request, such as user-specific content or real-time queries. For blogs, portfolios and documentation sites, static rendering is perfectly sufficient. It is faster and needs no running server process.

How much memory and CPU does an Astro site need in a container?

In my test on a server with 2 vCPUs and 4 GB RAM, the Nginx container used 8 MiB after 20,000 requests. The Node.js container used 70 MiB at idle and 153 MiB after the test. The Nginx image is 94 MB, the Node.js image with node:lts-alpine is 443 MB.

Why is my Node.js image so large?

The base image node:lts (Debian) alone weighs about 1.8 GB. With node:lts-alpine, the finished image shrinks from 1.97 GB to 443 MB. With a purely static site you avoid the problem, because only Nginx ends up in the final image.

How do I update my website on the server?

Change the code locally, test it and push it with Git. On the server, run git pull and then docker compose up --build -d. That rebuilds the image and replaces the container. With docker image prune -f, you clear out old images.

How do I get HTTPS for my Astro site?

Put a reverse proxy like Caddy in front of the container. You create an A record for your domain, add Caddy to the compose.yml and enter the domain in the Caddyfile. Caddy gets the certificate from Let's Encrypt on its own. The exact configuration is in the section on domain and HTTPS.

Why is my container reachable from outside despite ufw?

Docker writes published ports directly into the kernel's firewall rules, and ufw doesn't see these rules. So publish ports that should stay private with 127.0.0.1 in front (for example 127.0.0.1:8080:80), or block them in your provider's cloud firewall.

Can I host multiple Astro projects on one VPS?

Yes. Each project gets its own container. In front of them, you put a reverse proxy like Caddy or Traefik, which routes to the right container based on the domain. Alternatively, you publish each project on its own port.

Nginx or Apache for static Astro sites?

I use Nginx: it is in the official Astro Docker recipe, the image is small and the configuration is short. Apache serves static files just as well.

Conclusion

Astro.js and Docker work well together. Astro delivers performance and developer experience, Docker ensures consistent, portable deployments. With the Dockerfiles, the compose.yml and the Caddy configuration from this post, your site gets onto your own server in a few minutes, over HTTPS under your domain.

If you want to run more services on the same server, a shared reverse proxy pays off: my post Set up a server with Traefik as a reverse proxy shows how that works with Traefik. If you have questions or feedback, feel free to leave a comment.

Share
XRedditEmail
Back to all posts

Changelog

  1. Tested with Astro 7. Rewrote the deployment section, switched the Dockerfiles to node:lts-alpine and npm ci, updated the Nginx configuration (real 404, cache headers), added measurements and screenshots.

  2. Dockerfiles updated (node:lts, optimized multi-stage pattern), text expanded, FAQ section added.

Related articles

Comments