Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 33 ยท Testing, Security and Production

Deploying Medusa

Deploy a Medusa 2 backend: server and worker modes, the admin build, Postgres, Redis and S3, Docker, migrations in the release step and health checks.

Running medusa develop on your laptop hides a lot: an in-memory event bus, local file storage, a dev database and an admin that rebuilds as you type. A production deployment replaces each of those with something durable, and it splits the application into roles so web traffic and background work do not fight for the same process.

This lesson walks through what a production Medusa backend needs: the build, the server and worker modes, the supporting services (Postgres, Redis, file storage), a Docker image, the release steps (migrations first), health checks and the choice between Medusa Cloud and self-hosting. Platform code and configuration are read-only; the stand-ins validate environment variables and show which parts of the app each mode starts.

What a production setup contains

flowchart LR
    U["Browsers and storefront"] --> LB["Load balancer"]
    LB --> S1["Server instance<br/>serves API and admin"]
    LB --> S2["Server instance"]
    S1 --> PG[("Postgres")]
    S2 --> PG
    W["Worker instance<br/>subscribers, jobs, workflows"] --> PG
    S1 --> R[("Redis")]
    S2 --> R
    W --> R
    S1 --> F["File storage<br/>S3-compatible"]

Servers answer HTTP; a worker runs background work; Redis lets them share events and workflow state.

The pieces:

  • Postgres holds all module data. Use a managed database with backups.
  • Redis powers the Redis event bus, the workflow engine for long-running workflows, the cache and locking modules. Without Redis, those use in-memory implementations that only work in a single process.
  • File storage: the local file provider writes to disk, which disappears with a container. Use the S3 file provider (works with Amazon S3 and S3-compatible stores).
  • Server and worker processes from the same code base, started with different settings.

Server mode versus worker mode

Subscribers (Events and Subscribers) and scheduled jobs (Scheduled Jobs) should not run inside every web instance. If three servers each ran the nightly sync job, it would run three times. Medusa's workerMode setting separates the roles (read-only):

TypeScript
module.exports = defineConfig({
  projectConfig: {
    databaseUrl: process.env.DATABASE_URL,
    redisUrl: process.env.REDIS_URL,
    workerMode: process.env.MEDUSA_WORKER_MODE as "shared" | "worker" | "server",
    http: {
      storeCors: process.env.STORE_CORS!,
      adminCors: process.env.ADMIN_CORS!,
      authCors: process.env.AUTH_CORS!,
      jwtSecret: process.env.JWT_SECRET!,
      cookieSecret: process.env.COOKIE_SECRET!,
    },
  },
  admin: {
    disable: process.env.DISABLE_MEDUSA_ADMIN === "true",
    backendUrl: process.env.MEDUSA_BACKEND_URL,
  },
})
Mode Serves HTTP Runs subscribers, jobs, workflow background work
shared (default) yes yes
server yes no
worker no (only health endpoints) yes

Locally and for a tiny store, shared is fine. In production, run N server instances behind the load balancer and one or more worker instances. Scaling the web tier then never multiplies your cron jobs. A worker only receives events if the event bus is Redis-backed; with the in-memory bus, events stay inside the process that emitted them.

The admin dashboard

The admin is a React single-page app that medusa build compiles. Two common patterns:

  1. Served by the server instances. Simplest: the build output includes the admin and the server serves it at /app.
  2. Disabled on servers or workers. Set DISABLE_MEDUSA_ADMIN=true on the worker, which never needs it, and optionally on API-only servers if you host the admin elsewhere.

Set MEDUSA_BACKEND_URL to the public URL of the API so the dashboard knows where to send requests. Remember that the admin origin must also appear in adminCors (Security and Performance).

Build and start

On the build machine (read-only commands):

Terminal
npm ci
npx medusa build

medusa build compiles the backend and the admin into a .medusa/server folder (check your version's output path in the docs, it has changed between releases). That folder is the deployable unit: install production dependencies inside it, provide the environment variables and start it:

Terminal
cd .medusa/server
npm ci --omit=dev
npx medusa start

Never run medusa develop in production: it watches files, rebuilds the admin and is far slower.

Docker

A multi-stage Dockerfile keeps the image small. A sketch (read-only; adapt the Node version and paths to your project):

DOCKERFILE
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npx medusa build

FROM node:22-alpine
WORKDIR /app
COPY --from=build /app/.medusa/server ./
RUN npm ci --omit=dev
ENV NODE_ENV=production
EXPOSE 9000
CMD ["npx", "medusa", "start"]

The same image runs as a server or a worker; only the MEDUSA_WORKER_MODE and DISABLE_MEDUSA_ADMIN variables differ. Do not bake secrets into the image: pass them at run time. For building and shipping images in general, see the Docker tutorial's lessons on multi-stage builds and registries.

Migrations belong in the release step

When you add a model or upgrade Medusa, the database schema must change before the new code takes traffic. Run migrations once per release, as their own step (read-only):

Terminal
npx medusa db:migrate

Do not run them from every starting instance: parallel migrations race each other. The safe order is:

  1. Build the image.
  2. Run medusa db:migrate against the production database in a one-off release task.
  3. Roll out the new server and worker instances.

Design migrations to be backward compatible (add a column before the code that uses it), so old instances keep working while the new ones start. Take a database backup before migrating major upgrades.

Environment variables

A typical production set:

Variable Purpose
DATABASE_URL Postgres connection string
REDIS_URL Redis for events, workflows, cache, locking
JWT_SECRET, COOKIE_SECRET Token and cookie signing
STORE_CORS, ADMIN_CORS, AUTH_CORS Allowed browser origins
MEDUSA_BACKEND_URL Public API URL used by the admin
MEDUSA_WORKER_MODE server or worker
DISABLE_MEDUSA_ADMIN true on instances without the dashboard
Provider keys Stripe, email, S3 credentials

Stand-in 1: an environment validator

Failing fast beats discovering a missing secret during the first checkout. This validator checks required variables, rejects development defaults in production and applies mode-specific rules. It mirrors the logic you would put at the top of medusa-config.ts.

JS Validate environment variables at startup

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

No output.

Stand-in 2: what each mode starts

This tiny model shows why server plus worker avoids duplicate jobs. It builds a "deployment" of three instances and counts how many times a nightly job would run.

JS Server and worker modes

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

No output.

Health checks and rollout

Medusa exposes a /health endpoint that returns a plain success response when the process is up. Point your load balancer and orchestrator at it so traffic only reaches ready instances and failed ones are restarted. Keep these habits:

  • Readiness before traffic. Start the new instances, wait for /health, then shift traffic.
  • Logs to stdout so your platform collects them, and an error tracker for unhandled exceptions.
  • Backups and restores tested. An untested backup is a hope, not a backup.
  • One worker is a single point of failure for jobs. That is acceptable if you can restart it quickly; run two only if your jobs and subscribers are idempotent (Idempotency).

For capacity planning and multi-region thinking, see Architecture and scaling.

Medusa Cloud or self-hosted?

Medusa offers a managed cloud that handles builds, databases, Redis and scaling for you; the trade-off is cost and less control. Self-hosting (a VPS with Docker, a container platform, Kubernetes) is cheaper at small scale and fully flexible, and everything in this lesson applies. Pick based on your team: if nobody wants to be on call for Postgres and Redis, managed is worth it. Offerings and pricing change, so check the current Medusa documentation before deciding.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why run scheduled jobs on a separate worker instead of every server?

    Jobs and subscribers run in every instance started in shared mode. Splitting into server and worker modes keeps background work to the worker, no matter how many servers you add.
  2. 2. When should medusa db:migrate run in a deployment?

    Migrations should run once per release against the database. Parallel migrations from many instances race each other.
  3. 3. What is wrong with the local file provider in a container deployment?

    Container filesystems are ephemeral. Use an S3-compatible provider so uploads survive deployments and are shared by all instances.
  4. 4. Which command starts the compiled production backend?

    develop is for local work with file watching. After medusa build you install production dependencies in the output folder and run medusa start.
  5. 5. What does the environment validator stand-in do with a weak JWT_SECRET in production?

    Failing fast on a missing or weak secret is safer than running with a forgeable-token configuration.

Summary

  • Production replaces development defaults: managed Postgres, Redis for events, workflows and cache, and S3-compatible file storage.
  • Use server instances for HTTP and worker instances for subscribers and jobs; shared mode is for small setups.
  • medusa build produces the deployable output; run medusa start there, never medusa develop.
  • Run medusa db:migrate once per release, before new instances take traffic.
  • Validate environment variables at startup, keep secrets out of images and watch /health.
  • Choose Medusa Cloud for less operations work or self-host for control and lower cost at small scale.

Next: Project: A Product Reviews Module