Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 37 ยท Deploy and Interop

Deploy, Compile and Docker: Shipping Deno Apps

Put a Deno app into production. Compare Deno Deploy, a compiled single binary, Docker and a Linux server, and learn env configuration, health checks, graceful shutdown, cron jobs and logging.

An app that works on your laptop is only half the job. This lesson covers the other half: getting a Deno program in front of users and keeping it healthy. Deno offers several routes, and the right one depends on how much infrastructure you want to manage:

Route You manage Best for
Deno Deploy almost nothing web apps and APIs, edge latency, KV, quick start
deno compile binary a server or a CLI distribution one file to copy, CLI tools, simple VPS
Docker image containers and a platform Kubernetes, Fly.io, ECS, Cloud Run, any registry
systemd on a VPS the whole machine full control, a single box

Whatever you choose, the application code should follow a few rules that make it deployable anywhere. We start with those, because they matter more than the platform.

Deploying needs accounts, servers and a Deno installation, none of which exist in the editor. Commands and config are read-only. The runnable examples cover the application side: configuration from environment variables and graceful shutdown, written with Node 24 APIs that mirror the Deno ones.

Twelve-factor habits for any platform

  1. Read configuration from the environment, with a clear error when something is missing.
  2. Listen on the port the platform gives you (PORT) and bind to 0.0.0.0 in containers.
  3. Log to standard output, one line per event, ideally JSON.
  4. Expose a health endpoint, so load balancers can check the app.
  5. Shut down gracefully when asked to stop.
  6. Keep the filesystem disposable: store files and data in a database or object storage.

This stand-in validates configuration at startup. Failing fast with a readable message is better than crashing later with undefined.

Node.js Validate configuration at startup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Health checks and graceful shutdown

TypeScript
// main.ts
const port = Number(Deno.env.get("PORT") ?? "8000");

const server = Deno.serve({ port, hostname: "0.0.0.0" }, (req) => {
  const { pathname } = new URL(req.url);
  if (pathname === "/healthz") return new Response("ok");
  return new Response("Hello from production");
});

async function shutdown(signal: string) {
  console.log(JSON.stringify({ level: "info", msg: "shutting down", signal }));
  await server.shutdown();        // stop accepting, finish in-flight requests
  // close database connections here
  Deno.exit(0);
}

Deno.addSignalListener("SIGTERM", () => shutdown("SIGTERM")); // sent by Docker, Kubernetes, systemd
Deno.addSignalListener("SIGINT", () => shutdown("SIGINT"));   // Ctrl+C

When a platform deploys a new version it sends SIGTERM and then waits a short time before killing the process. A graceful shutdown lets requests that are in progress complete. The stand-in below shows the effect with a real local server: a slow request is still answered after shutdown starts, and new connections are refused.

Node.js Graceful shutdown (Node stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Route 1: Deno Deploy

Deno Deploy runs your code on a global network of data centers, close to users, with no servers to manage and Deno KV built in. You connect a GitHub repository (or use the CLI), choose an entry point, and every push builds and deploys. Pull requests get preview URLs.

Terminal
deno deploy              # deploy from the CLI (needs a Deploy account and org)

The Deploy platform and its CLI have changed more than once, so follow the current instructions in the Deno documentation for exact setup steps. The things that stay true:

  • Your app is a standard Deno.serve handler; no special framework API.
  • Environment variables and secrets are set in the dashboard, never in code.
  • Instances are short-lived and may run in many places, so never keep important state in memory or on disk. Use KV or a database.
  • Check which Deno APIs and permissions are available on the platform before relying on them (for example raw file writes and subprocesses are limited).

Scheduled jobs with Deno.cron

TypeScript
Deno.cron("cleanup expired sessions", "0 * * * *", async () => {
  // runs at the start of every hour
  const kv = await Deno.openKv();
  // ...delete old records
});

Deno.cron("daily report", { hour: { every: 24 } }, () => { /* ... */ });

The schedule is a standard cron expression: minute, hour, day of month, month, day of week. Deno.cron runs on the platform without an external scheduler. It may require an unstable flag locally (--unstable-cron) depending on your version.

Route 2: deno compile

deno compile bundles your program, its dependencies and the Deno runtime into one executable file:

Terminal
deno compile --allow-net --allow-env --output server main.ts
./server                     # runs without Deno installed

Cross-compile for other systems:

Terminal
deno compile --target x86_64-unknown-linux-gnu --allow-net -o server-linux main.ts
deno compile --target aarch64-apple-darwin -o app-mac main.ts
deno compile --target x86_64-pc-windows-msvc -o app.exe main.ts

The permission flags you give at compile time are baked in, so users cannot change them. Static files can be included with --include ./public, and read at runtime relative to import.meta.dirname. Binaries are tens of megabytes because they carry the runtime. They are ideal for CLI tools you hand to users, and for copying one file to a server.

Route 3: Docker

The official image denoland/deno has the runtime and the right defaults. A production Dockerfile:

DOCKERFILE
FROM denoland/deno:2.1.4

WORKDIR /app

# 1. dependencies first, so this layer is cached until they change
COPY deno.json deno.lock ./
RUN deno install --frozen

# 2. then the application code
COPY . .
RUN deno cache main.ts

# run as the non-root user the image provides
USER deno

EXPOSE 8000
ENV PORT=8000

# the image's entrypoint is "deno", so CMD holds its arguments
CMD ["run", "--allow-net", "--allow-env=PORT,DATABASE_URL", "main.ts"]
Terminal
docker build -t my-app .
docker run -p 8000:8000 --env DATABASE_URL=postgres://... my-app

Tips: pin an exact image version for repeatable builds; copy deno.json and deno.lock before the source so dependency installation is cached; run as a non-root user; use the narrowest permission flags; and add a .dockerignore for node_modules and .git. Compose and registries are covered in our Docker tutorial.

Route 4: a Linux server with systemd

INI
# /etc/systemd/system/my-app.service
[Unit]
Description=My Deno app
After=network.target

[Service]
User=app
WorkingDirectory=/srv/my-app
EnvironmentFile=/srv/my-app/.env
ExecStart=/usr/local/bin/deno run --allow-net --allow-env main.ts
Restart=on-failure
KillSignal=SIGTERM
TimeoutStopSec=15

[Install]
WantedBy=multi-user.target
Terminal
sudo systemctl enable --now my-app
journalctl -u my-app -f        # follow the logs

Put a reverse proxy such as Caddy or nginx in front to terminate HTTPS and serve on ports 80 and 443. The app keeps listening on a local port.

Observability

Print structured logs to standard output, and the platform collects them:

TypeScript
function log(level: string, msg: string, extra: Record<string, unknown> = {}) {
  console.log(JSON.stringify({ time: new Date().toISOString(), level, msg, ...extra }));
}
log("info", "request handled", { path: "/api/users", ms: 12 });

Recent Deno versions also include built-in OpenTelemetry support: set OTEL_DENO=true and standard OTEL_* variables and Deno exports traces, metrics and logs for fetch, Deno.serve and console output to your collector. Check the current docs for the Deno version you run.

Pre-launch checklist

  • Tests, deno lint, deno fmt --check and deno check pass in CI.
  • deno.lock is committed and installs use --frozen.
  • Permissions are the minimum the app needs.
  • Config and secrets come from the environment; no secrets in the repository.
  • /healthz exists; shutdown is graceful.
  • Logs go to stdout; errors are captured somewhere you will see them.
  • You can roll back to the previous version quickly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does deno compile produce?

    The output runs on a machine without Deno installed, with the compile-time permissions baked in.
  2. 2. Why copy deno.json and deno.lock into the image before the rest of the source?

    Docker caches layers in order. Dependencies change rarely, so installing them in an early layer saves build time.
  3. 3. Which signal do Docker and Kubernetes send first to ask a process to stop?

    SIGTERM asks the app to stop gracefully. If it ignores it, SIGKILL follows after a timeout.
  4. 4. Why shouldn't a Deno Deploy app keep important data in a global variable?

    Use KV or a database for state that must survive restarts or be seen by every instance.

Summary

  • Make apps deployable anywhere: env configuration, PORT, stdout logs, health endpoint, graceful shutdown.
  • Deno Deploy is the hands-off route; deno compile makes one binary; Docker fits container platforms; systemd plus a reverse proxy suits a single server.
  • Deno.cron schedules jobs; keep state in KV or a database.
  • Pin versions, commit deno.lock, run as non-root and grant minimal permissions.

Next: Project: URL Shortener