Docker

Deploy a Docker container

Run any app that has a Dockerfile, in any language, with a managed database and environment variables set per environment. This guide goes from a small Go server to a production deploy on Modelence.

Last updated /Tested with Docker 29.1, Go 1.27 and Alpine 3.24

To deploy a Docker app, add a modelence.config.json that points at your Dockerfile and run npx modelence@latest deploy. Modelence builds the image and runs it as managed containers on AWS, in the region you pick out of 17, with managed MongoDB, Postgres and Redis next to it.

A Dockerfile works the same whatever language is inside it, so these steps fit a backend in Go, Python, Ruby or Java, or a Node.js app that needs system packages. The guide writes a small Go server and its Dockerfile, runs the container locally, connects it to a database and deploys it. If you already have an app with a Dockerfile, skip to Write the Dockerfile.

Docker on Modelence at a glance

How it runs
Your Dockerfile builds the image, which runs with its own CMD, USER and WORKDIR on AWS Fargate, across two availability zones
Regions
17 AWS regions in the Americas, Europe and Asia Pacific, with the containers and databases in the same one
Databases
Managed MongoDB, Postgres and Redis, each connection string passed to the container as an environment variable
Backups
Production databases are backed up at least every six hours, with snapshots encrypted at rest
Deploys
New containers start and pass health checks before the old ones stop, and a version that keeps crashing rolls back
Logs
Whatever the container writes to stdout and stderr shows on the Logs page, with nothing to set up
Price
Free plan to start; paid plans from $20 a month with $20 of usage included, containers from about $9 a month

Before you start

  • Docker on your machine, to build and test the image
  • Go 1.27 for the example app, or your own app in any language
  • Node.js on your machine, to run the deploy command with npx
  • A Modelence account, which you can create for free
  • Optionally, Claude Code, Cursor or Codex, if you'd rather have your coding agent write the Dockerfile and the config and run the deploy

Create a small web server

The example is a Go server with two routes that uses only the standard library. Create a module:

mkdir hello && cd hello
go mod init example.com/hello

Then add main.go. The server reads its port from the PORT variable and falls back to 3000 on your machine. Modelence sets PORT in production, and a server that listens on a hardcoded port never receives traffic. The address ":" + port listens on all interfaces, which a container needs, because its traffic comes from outside it. Start the server with go run . and open http://localhost:3000.

main.go
package main

import (
	"encoding/json"
	"log"
	"net/http"
	"os"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]string{"message": "Hello from Docker"})
	})
	mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("ok"))
	})

	port := os.Getenv("PORT")
	if port == "" {
		port = "3000"
	}
	log.Printf("Listening on port %s", port)
	log.Fatal(http.ListenAndServe(":"+port, mux))
}

Write the Dockerfile

Add a Dockerfile next to go.mod. It is a multi-stage build: the first stage compiles the server, and the second copies only the binary into a small Alpine image, so the image that runs holds neither the Go toolchain nor the source.

  • Base images come from public.ecr.aws/docker/library/, a mirror of Docker Hub's official images. Docker Hub limits how often images can be pulled, so a build that pulls golang:1.27 from it can fail on that limit.
  • Match the golang tag to the go line in go.mod.
  • go.mod is copied and the dependencies downloaded before the rest of the source, so a code change reuses the cached dependency layer. go.sum* picks up go.sum once the module has dependencies.
  • CGO_ENABLED=0 builds a static binary that runs on Alpine.
  • USER 65534 runs the server as the unprivileged nobody user instead of root.
  • CMD uses the exec form, so the SIGTERM a stopping container gets reaches the server and not a shell in front of it.

For another language, start from its official image on the same mirror, install the dependencies from the lockfile before copying the source, and start a production server. Dockerfile services has a Python example.

Dockerfile
FROM public.ecr.aws/docker/library/golang:1.27 AS build
WORKDIR /src
COPY go.mod go.sum* ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/server .

FROM public.ecr.aws/docker/library/alpine:3.24
COPY --from=build /out/server /server
USER 65534
CMD ["/server"]

Build and run the container locally

Add a .dockerignore next to the Dockerfile, so the build context leaves out the Git history and local secrets. For other languages, also list dependency folders such as node_modules or .venv and the build output:

.git
.env
*.env

Then build the image and run it with PORT set, the way Modelence runs it, and check that the app answers on http://localhost:3000 and http://localhost:3000/health. A deploy runs the same build, so anything that fails here fails there too.

bash
docker build -t hello .
docker run --rm -e PORT=3000 -p 3000:3000 hello

Add a database

  • MongoDBMONGODB_URI
  • PostgresDATABASE_URL
  • RedisREDIS_URL

A container reads its database connection strings from environment variables, so any language works with Modelence's managed MongoDB, Postgres and Redis. They run in the same region as the app, connections use TLS and production databases are backed up at least every six hours.

Your code reads each connection string from the environment, the same way in any language, such as os.Getenv in Go or os.environ in Python: MONGODB_URI for MongoDB, and for Postgres and Redis the variable you tie to the database in modelence.config.json, usually DATABASE_URL and REDIS_URL. In Go, pass it to the client the app already uses, such as pgxpool.New from pgx, redis.ParseURL from go-redis or ApplyURI in the MongoDB driver, and create the client once when the server starts rather than on every request.

The variables are set when the container starts and don't reach the image build, so don't connect to a database in a RUN step.

If the app ran with Docker Compose, its postgres, redis or mongo containers become these managed databases, and the code reads the connection string from the variable instead of a Compose hostname such as db:5432. A database hosted elsewhere, such as Supabase or Neon, needs no code change, and its URL goes in env with "type": "secret".

Run migrations against the environment's database before you deploy, not in the Dockerfile's CMD. Every container runs CMD, several at once during a rollout, so migrations there would run in parallel, and a slow one would be cut off by the health check.

Add Postgres or Redis as resources in modelence.config.json next to the container's service, and the deploy creates them before the new version comes up:

modelence.config.json
{
  "resources": {
    // "api": the app's service, as in the next step
    "main-db": { "type": "postgres", "plan": "postgres-1gb" },
    "cache": { "type": "redis" }
  },
  "env": {
    "DATABASE_URL": { "type": "resource", "resource": "main-db", "output": "url" },
    "REDIS_URL": { "type": "resource", "resource": "cache", "output": "url" }
  }
}

Describe the app in modelence.config.json

A service that sets dockerfile is built from your Dockerfile, and Modelence runs the image as the Dockerfile leaves it, with its CMD, ENTRYPOINT, USER and WORKDIR. Add modelence.config.json at the root of the repository and commit it with the app and the Dockerfile:

modelence.config.json
{
  "$schema": "https://cloud.modelence.com/schema/modelence.config.json?version=1",
  "resources": {
    "api": {
      "type": "service",
      "dockerfile": "Dockerfile"
    },
    "main-db": { "type": "postgres", "plan": "postgres-1gb" }
  },
  "env": {
    "DATABASE_URL": { "type": "resource", "resource": "main-db", "output": "url" },
    "STRIPE_SECRET_KEY": { "type": "secret" }
  }
}

Adjust the config for your project

  • The Go server reads PORT, so it listens on 3000, the default, and needs no ports key. An app that listens on a fixed port lists it in ports, main port first, for example "ports": [8000] for uvicorn main:app --host 0.0.0.0 --port 8000. The container gets the main port as PORT either way.
  • The server has to listen on 0.0.0.0. uvicorn, gunicorn and flask run listen on 127.0.0.1 by default, and a process listening there never receives traffic or health checks. Start a production server, such as gunicorn or uvicorn without --reload, not flask run or manage.py runserver.
  • If the app lives in a subdirectory of a monorepo, set root to it, such as "root": "services/api". root is the build context, so the build sees only the files under it, and dockerfile is relative to it.
  • To start the image with a different command than its CMD, set "start": { "commands": ["..."] }. The commands run under /bin/sh -c.
  • Declare keys and tokens with "type": "secret" and no value. The deploy asks you for them in the browser, and you can change them later in the dashboard under Environment variables, where every view of a secret is logged.
  • A variable the image build needs gets "scopes": ["build", "runtime"]. A value written in the file reaches the Dockerfile as a build argument that you declare with ARG, and a value set in the dashboard arrives as a BuildKit secret, so it never ends up in an image layer. Variables in the build shows how to read it.
  • To run the app on your machine with the environment's variables, add "dev": { "commands": ["go run ."] } to the service, run npx modelence@latest setup once and then start the app with npx modelence@latest dev. It runs the dev commands directly on your machine, not in Docker.
  • A Node.js app that needs no system packages deploys without a Dockerfile, as described in Deploy a Node.js app.

Deploy

Run the deploy command in the project directory:

npx modelence@latest deploy

It opens the browser, where you sign in, pick the organization, app and environment (or create them) and enter any required variables the environment doesn't have yet, such as STRIPE_SECRET_KEY above. Then it uploads the project, builds the image from your Dockerfile and follows the build until the app is live. You pick the AWS region the first time you deploy an environment, and its containers and databases are created there. Next time, pass --app <app> --env <env> to preselect the target.

The first deploy creates the databases in resources, starts the app once they're ready and attaches the environment's URL, <app>-<environment>.cloud.modelence.app, to the api service. To use your own domain, add it in the dashboard under Domains. Every app has a sandbox and a production environment, and the same file deploys to both.

Let your coding agent do it

Paste Deploy using https://modelence.com/skill.md into Claude Code, Cursor or Codex in your project. The agent reads the docs, writes a Dockerfile if the project has none, writes modelence.config.json, builds and runs the image locally and runs the deploy, and it stops to ask you whenever a step needs your account.

Production readiness

Add a health check

By default Modelence counts a container as healthy once it accepts connections on its main port. An HTTP check is stricter: the container has to answer a path with a 2xx status within 4 seconds, so a new version that starts but can't serve requests never takes traffic. The example server already has a /health route. Point the service's check at it in modelence.config.json:

"healthCheck": { "type": "http", "path": "/health" }

Redirects are followed, so the route should answer 2xx itself, before any middleware that redirects or rejects signed-out requests. For an app that loads a model or warms a cache before it listens, raise gracePeriod in the check, 60 seconds by default.

Shut down cleanly

When a container stops, for example during a deploy, the process gets SIGTERM, and requests can still reach it for about 10 seconds after that. To finish them without dropping any, keep serving for 10 to 15 seconds, then close the server and exit. In Go, run the server in a goroutine and wait for the signal:

srv := &http.Server{Addr: ":" + port, Handler: mux}
go func() {
	if err := srv.ListenAndServe(); err != http.ErrServerClosed {
		log.Fatal(err)
	}
}()

ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
<-ctx.Done()

time.Sleep(10 * time.Second)
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
srv.Shutdown(shutdownCtx)

The signal only reaches the server when CMD uses the exec form, or exec in a shell form. The container gets 30 seconds between SIGTERM and SIGKILL by default, which leaves time for this. Change it with stopTimeout on the service.

Move volumes to managed storage

Volumes and bind mounts from docker run -v or a Compose file don't carry over, since containers on Modelence have no persistent disk and start clean on every deploy. Data the app wrote to a volume belongs in one of the managed databases, uploaded files in object storage, and sessions or caches in Redis.

Once the container keeps no state of its own, run two or more of them under Configure so a crash or a zone outage doesn't take the app down. Availability has the details on rollouts and rollbacks.

Run background jobs as their own service

Don't run a queue consumer or a scheduled job inside the web server. With several containers, each one would run every job, and emails or charges would go out twice. Add a second service to modelence.config.json with its own Dockerfile:

"worker": {
  "type": "service",
  "dockerfile": "worker.Dockerfile",
  "healthCheck": { "type": "none" },
  "rollout": "recreate"
}

The worker listens on no port, so it has no health check, and "rollout": "recreate" stops the old worker before the new one starts. Keep it on one container if its jobs must not run twice, or have each job take a lock in the database. Multiple services has the details.

Watch logs and metrics

Logs need no setup. Everything the container writes to stdout and stderr shows on the environment's Logs page. For traces and metrics, add a telemetry resource and tie OTEL_EXPORTER_OTLP_ENDPOINT and OTEL_EXPORTER_OTLP_HEADERS to its outputs, so the OpenTelemetry SDK in your app sends them to the environment's Monitoring page. Set OTEL_LOGS_EXPORTER to none, since logs are already collected. Deploy setup has the full example.

Modelence vs Railway, Render and Fly.io for Docker containers

Railway, Render and Fly.io are the platforms people compare most often for hosting a Dockerfile app, and all of them, like Modelence, build the image from a Dockerfile in your repository. Prices and limits below come from each platform's own pricing page and docs, checked on November 24, 2026.

How a Docker app runsDatabasesRegionsPricing modelBest for
ModelenceBuilds your Dockerfile and runs the image on AWS Fargate across two availability zonesManaged MongoDB, Postgres and Redis, backed up at least every six hours17 AWS regionsFree plan; paid plans from $20 a month including $20 of usage, then containers billed by the hour by sizeProduction apps and workers on AWS, with the databases managed in the same region
RailwayUses a Dockerfile at the root of the source directory, or the path in RAILWAY_DOCKERFILE_PATHPostgres, MySQL, Redis and MongoDB from templates on volumes, with backups you turn on4: California, Virginia, Amsterdam and SingaporeFree plan with $1 of usage a month; Hobby $5 and Pro $20 a month including that much usage, then CPU and memory by the secondServices whose load comes and goes, since idle ones cost little
RenderBuilds the repository's Dockerfile with BuildKit, or pulls a prebuilt image from a registryManaged Postgres and Redis-compatible Key Value5: Oregon, Ohio, Virginia, Frankfurt and SingaporeWorkspace plan ($0 Hobby, $25 Pro) plus a fixed price per instance, from $7 a month for 512 MBServices that run steadily, at a predictable price per instance
Fly.iofly launch detects the Dockerfile, and fly deploy builds it on a remote builder and rolls it out to MachinesManaged Postgres from $4 a month; volumes are local NVMe drives tied to one Machine17, including Johannesburg, São Paulo and SydneyEach Machine billed by the second, from $2.19 a month for shared-cpu-1x with 256 MBSmall containers at a low monthly price, in many regions

Fly.io is the better fit for a very small container on a tight budget, or for a region such as Johannesburg that Modelence doesn't run in. Render suits a service that runs at a steady load and is easiest to budget per instance, and Railway suits several small services that sit idle much of the day. Modelence fits when the app should run on AWS with MongoDB, Postgres and Redis managed and backed up in its own region, and when you'd rather have a coding agent write the config and run the deploy. Railway vs Render compares those two in more depth, and Railway alternatives covers the wider field.

Next steps

Frequently asked questions

How do I deploy a Docker container to production?

Use a platform that builds your Dockerfile and runs the image as managed containers, so you don't run servers yourself. On Modelence you add a modelence.config.json that names the Dockerfile and run npx modelence@latest deploy, and the image is built and run on AWS in the region you pick, for any language that serves HTTP on a port. Build and run the image locally with docker build and docker run first, since the deploy runs the same build.

Can I host a Docker container on AWS without managing AWS myself?

Yes. Modelence runs your containers on AWS Fargate and manages them, along with the databases and their backups, so you don't set up ECS services, load balancers or IAM roles. You describe the app in modelence.config.json and pick one of 17 regions the first time you deploy, and its containers and databases are created there.

Do I need Kubernetes to run Docker containers in production?

No, not for a typical web app, API or worker. On Modelence each service runs on AWS Fargate across two availability zones, a container that fails its health checks is replaced, and a deploy starts the new version before it stops the old one. Kubernetes gives you more control, at the cost of a cluster that you have to operate and keep up to date.

Can I deploy a Docker Compose app?

Yes, by describing the same processes in modelence.config.json, since the Compose file itself isn't read. Each Compose entry with build: becomes a service built from its own Dockerfile, up to 5 per environment, and a postgres, redis or mongo container becomes a managed database whose connection string reaches the app as an environment variable. The services share a private network, so they reach each other without public URLs.

Can I deploy a prebuilt image instead of a Dockerfile?

Not straight from a registry, because Modelence builds every service from a Dockerfile in your repository. To run a public image as it is, commit a Dockerfile with a single FROM line naming that image, as long as the image listens on the service's main port. For an official Docker Hub image, pull it from public.ecr.aws/docker/library/ instead, since Docker Hub limits how often images can be pulled.

Does data inside a container survive a restart or redeploy?

No. Containers on Modelence have no persistent disk, so files written inside one are gone when a deploy or a restart replaces it, and volumes from docker run -v or a Compose file don't carry over. Keep records in the managed MongoDB, Postgres or Redis databases, which are backed up, and uploaded files in object storage.

Which port should my container listen on?

The port in the PORT variable, which is 3000 unless you set ports in modelence.config.json. Either read PORT, or listen on a fixed port and list it first in ports. Listen on 0.0.0.0, not 127.0.0.1, so traffic and health checks from outside the container reach the app.

How do I pass environment variables and secrets to the container?

Declare them in the env section of modelence.config.json, and set secret values in the dashboard, where they can be viewed and every view is logged. Runtime variables are set in the container's environment when it starts, next to PORT and the database connection strings. A variable scoped to the build reaches the Dockerfile as a build argument when its value is in the file, or as a BuildKit secret when it is set in the dashboard, so it never ends up in an image layer.

Can I use my own domain?

Yes, on any paid plan, which includes unlimited custom domains. Add the domain in the dashboard under Domains and attach it to the service and port that serve the app.

How much does it cost to host a Docker container on Modelence?

You can start for free: the free plan runs one container that sleeps when idle. Paid plans start at $20 a month with the same amount included as cloud usage, and add managed Postgres and Redis, custom domains and more than one service. Containers are billed by the hour by size, from about $9 a month for 0.25 vCPU and 0.5 GB of memory to about $202 a month for 4 vCPU and 16 GB.

Deploy other stacks

Deploy your Docker app

Start on the free plan and move up when your app needs more.

Or paste this into your coding agent