A Stacktape web service runs one always-on container with a public HTTPS URL. Use the WebService resource for APIs, backend web apps, and internet-facing container services that need TLS, health checks, horizontal scaling, and deployment behavior managed through Stacktape instead of hand-wired AWS networking.
Pricing context: Fargate bills for every running task; approximate us-east-1 monthly compute starts around ~$7.29/month per 0.25 vCPU plus ~$1.60/month per 512 MB memory. HTTP API Gateway load balancing is about ~$1/million requests; Application Load Balancer starts around ~$18/month plus usage.
When to use
A Stacktape web service is the right default for a single public HTTP container that should stay online all the time. Pick a web service when the workload serves request/response traffic, needs a stable HTTPS URL, and benefits from Stacktape-managed load balancing, TLS certificates, scaling, logs, and health checks.
Common use cases:
- Public APIs — REST, GraphQL, JSON-RPC, or framework-based HTTP APIs running in a container
- Backend web apps — Express, Fastify, Django, FastAPI, Spring Boot, Go HTTP servers, or similar long-running processes
- Containerized services with steady traffic — workloads where keeping at least one instance warm is worth the predictable latency
- Services needing custom domains or CDN routing — public endpoints where Stacktape can attach domains, certificates, and optional CloudFront caching
When NOT to use
- Scale-to-zero request handling — use a Lambda function when the workload is event-driven, idle most of the time, or should bill only on invocation.
- Internal-only services — use a private-service when the container should be reachable only from your stack or VPC.
- Background workers — use a worker-service when the container consumes queues or events without exposing a public endpoint.
- Multiple tightly-coupled containers — use a multi-container-workload when you need a workload model centered on multiple containers with their own integrations.
- Jobs that finish and exit — use a batch job for compute that runs to completion instead of serving traffic continuously.
Basic example
A basic Stacktape web service needs container packaging and compute resources. The default traffic path is http-api-gateway, so this example gets a public HTTPS URL without defining a separate load balancer resource.
entryfilePath points to the application entry point that js-bundle bundles. The resources block sets the Fargate task size for the container — cpu: 0.5 and memory: 1024 are explicit task-size selections, not implied defaults. Fargate is the default compute engine for web services unless you choose EC2 instance types through the resource configuration. See the API reference for the full resources configuration shape.
Traffic
A Stacktape web service can receive public traffic through three load balancing modes: http-api-gateway, application-load-balancer, and network-load-balancer. The default is http-api-gateway, which is usually the best first choice for HTTP APIs because pricing is request-based and Stacktape can still manage the public HTTPS endpoint.
| Mode | Best for | Tradeoff |
|---|---|---|
http-api-gateway | Most HTTP APIs and web apps | Pay-per-request pricing grows with volume; CORS support is available here |
application-load-balancer | WebSockets, gradual deployments, top-level useFirewall, and high steady HTTP traffic | Adds a baseline monthly load balancer cost |
network-load-balancer | TCP/TLS protocols such as MQTT, game servers, or custom protocols | Requires explicit ports; does not support CDN, top-level firewall, or gradual deployments |
Use application-load-balancer when the service needs WebSocket support, gradual deployments, or a regional web application firewall attached through top-level useFirewall. The ALB health check defaults are path /, interval 5 seconds, and timeout 4 seconds, and you can override those in loadBalancing.properties.
Use network-load-balancer only when the service is not ordinary HTTP. Each ports entry defines the public listener port, the protocol (TLS by default, or TCP), and optionally a different containerPort when the container listens on another port.
healthCheckProtocol: 'TCP' checks whether the port accepts connections; choose HTTP only when the container exposes a health path. port is the public Network Load Balancer listener, while containerPort is the port inside the container that receives traffic.
Domains and CORS
A Stacktape web service can attach custom domains directly through customDomains. Stacktape can auto-create DNS records and provision a free TLS certificate. The domain must first be added as a Route53 hosted zone in your AWS account, with the registrar's nameservers pointing to that hosted zone. Set disableDnsRecordCreation when DNS records are managed outside Stacktape.
This minimal form assumes Stacktape creates both the DNS record and TLS certificate automatically. Set disableDnsRecordCreation: true when you manage DNS records outside Stacktape. Use customCertificateArn when you want Stacktape to use an ACM certificate you already manage, such as one with specific certificate requirements. cors is available only with the default http-api-gateway load balancing mode and overrides CORS headers returned by your application, so prefer application-level CORS when the app needs route-specific behavior.
CDN
The cdn property on a Stacktape web service places a CloudFront CDN in front of the public endpoint for caching and lower latency worldwide. Enable CDN when globally accessed APIs have cacheable responses or when edge routing reduces latency; skip CDN for highly dynamic APIs where every request must reach the container and cache invalidation would add operational work.
The cdn path is separate from top-level load balancer configuration. A top-level useFirewall attaches a regional firewall to an Application Load Balancer and requires loadBalancing.type: 'application-load-balancer'; cdn.useFirewall protects the CloudFront distribution and uses a web-app-firewall resource with CDN scope.
For most API services, start without cdn and add it after measuring latency or origin load. CDN behavior, caching, and CloudFront-specific routing are covered in the CDN resource; the web service page only needs to decide whether the public container endpoint should be fronted by that layer.
Compute resources
A Stacktape web service uses the same container compute model as other Stacktape container workloads. Fargate is the default serverless compute engine: set cpu and memory, pay while tasks are running, and avoid managing EC2 instances. EC2 mode is available by specifying instanceTypes when you need instance-level control.
Fargate is right for most web services because it keeps operations simple and bills by allocated vCPU and memory while the container is running. AWS Fargate ARM (Graviton) tasks are approximately 20% cheaper than x86 in us-east-1.
Use EC2 mode for workloads that need specific instance families, GPU-capable instances, or cost optimization at high sustained utilization. EC2 mode gives more control over instance selection and capacity management.
instanceTypes selects EC2-based compute instead of Fargate. c6g.large is an example ARM (Graviton) instance type; choose instance families that match your container image architecture and workload profile. You can specify multiple instance types for capacity flexibility.
Scaling
A Stacktape web service scales horizontally by running more container instances and distributing traffic across healthy instances. The scaling property uses the ContainerWorkloadScaling configuration shared by all Stacktape container workloads. Use scaling when request volume changes enough that one fixed instance count is either too expensive during quiet periods or too small during peaks.
minInstances is the baseline number of running containers and therefore the baseline cost. maxInstances caps scale-out. CPU and memory scaling policies tell Stacktape when to add capacity; keeping both thresholds explicit is useful for web services where either CPU-bound request handling or memory pressure can be the first bottleneck.
minInstances low for non-production stages, and use a Lambda function when idle cost matters more than always-warm container latency.Packaging
A web service supports the same four container packaging types as other Stacktape container workloads. Start with js-bundle for a JavaScript or TypeScript service with one entry file, and with buildpack for everything else, including Next.js and other framework builds. Switch only when the container build needs more control.
| Type | When to use |
|---|---|
js-bundle | A JavaScript or TypeScript service with one entry file. Stacktape bundles it into a small image. |
buildpack | Build from source without a Dockerfile. Detects Node.js frameworks, Python, Go, Rust, Java, PHP, Ruby, .NET and more. |
dockerfile | Full control over the base image, system packages, build steps, entrypoint and command |
prebuilt-image | Deploy an image already built by another pipeline or stored in a registry |
js-bundle images are based on Alpine. Set requiresGlibcBinaries only when native dependencies such as sharp, canvas, bcrypt or puppeteer need glibc. A buildpack web service must listen on the port in the PORT environment variable; set startCommand if the detected start command does not.
Port
Stacktape sets the PORT environment variable and routes traffic to that port, 3000 by default. If your application listens on a fixed port, such as app.listen(8080) or a Spring Boot service on its default 8080, set port to that number instead of changing the code. stacktape init sets it when it finds a fixed port in your project. With network-load-balancer, loadBalancing.properties.ports[].containerPort sets the container port instead.
Changing port on a deployed service replaces the resources that route to the old port, so in-flight requests can fail during that update.
Connecting to other resources
A Stacktape web service can use connectTo to access other resources in the same stack. Stacktape grants IAM permissions where relevant, opens security group access for supported network resources, and injects environment variables with connection details following the STP_[RESOURCE_NAME]_[PARAM] naming pattern.
The example uses the RdsEnginePostgres class to construct a Postgres database. The stacktape package also exports RdsEngineMysql, RdsEngineMariadb, and Aurora engine variants for other database types. For connectTo on this web service, Stacktape follows the STP_[RESOURCE_NAME]_[PARAM] naming pattern: myDatabase provides STP_MY_DATABASE_CONNECTION_STRING, STP_MY_DATABASE_HOST, and STP_MY_DATABASE_PORT; uploadsBucket provides STP_UPLOADS_BUCKET_NAME and STP_UPLOADS_BUCKET_ARN. Use $ResourceParam() for parameters not in the connectTo injection table. For the full resource-by-resource list, see connecting resources. For permissions outside connectTo, add narrowly scoped iamRoleStatements.
For user-defined runtime configuration, use the environment property to pass static values, secrets via $Secret(), or resource parameters via $ResourceParam() directly into the container. Variables from connectTo are merged automatically alongside any environment entries you define.
Health checks
A Stacktape web service has two health-check layers. When using application-load-balancer or network-load-balancer load balancing, the load balancer health check determines whether traffic should be sent to a container. Separately, internalHealthCheck is a container-level health check that lets ECS auto-replace a container that is still running but no longer healthy.
For Application Load Balancer mode, configure load balancer health checks under loadBalancing.properties. For Network Load Balancer mode, health checks can use TCP or HTTP; healthcheckPath only applies when healthCheckProtocol is HTTP, and the health check port defaults to the traffic port.
Use an internal health check when the process can be alive while the application is broken, such as a server with a failed database pool or stuck event loop. If a container fails the internal health check, ECS treats the container as unhealthy and replaces it. Keep the health check command cheap and local to the container; checks that depend on slow external services can cause unnecessary replacement during transient dependency issues. See the API reference for the full internalHealthCheck configuration shape.
The default http-api-gateway mode has no health check. Stacktape can tell that a new task is running and registered for routing, but cannot tell whether the application works. A one-line internalHealthCheck enables application failure detection and automatic rollback when the check fails during deployment. For example, a Node.js service listening on port 3000 can use internalHealthCheck: { healthCheckCommand: ['CMD', 'node', '-e', "fetch('http://localhost:3000/health').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"] }. Use a command available in your image and an endpoint that returns success only when your app is ready.
How deploys replace containers
A deploy starts the new containers next to the old ones. Once every new container passes its health check, the old
containers stop receiving new requests, get 30 seconds to finish the requests they are handling, and shut down: ECS
sends SIGTERM and, if the process is still running after stopTimeout (default 30 seconds), SIGKILL. Handle
SIGTERM in your app so an old container exits once its requests are done. An app that ignores the signal keeps a full
deploy waiting for the whole stopTimeout.
A full deployment finishes after the old containers have stopped, because CloudFormation waits for that. A fast deployment, which Stacktape uses when only your code changed, lets the old containers drain and shut down in the background. When it finishes depends on your health checks and load balancing:
- Default
http-api-gateway, nointernalHealthCheck: the deploy finishes once every new task isRUNNINGand API Gateway can route to it, plus 4 seconds. Only tasks from the new deployment count; an old task still draining cannot satisfy this check. API Gateway sends requests to a new container within about 2 seconds of its start, even before your app listens. This confirms that the containers started, not that your app works: an app that stays running without listening, or returns errors, can still count as deployed. - Default
http-api-gatewaywithinternalHealthCheck: the deploy finishes 4 seconds after every new container has passed its check and API Gateway can route to it. A failing check stops the deploy and rolls it back. In our measurements, the first request reached the new containers at most 2.2 seconds after they became routable, and ECS removed the old containers from Cloud Map 8 to 22 seconds after the new ones passed the check. - Behind an
application-load-balancerornetwork-load-balancer: the deploy finishes 4 seconds after the load balancer reports every new container healthy in each of its target groups. The load balancer starts sending requests a few seconds after that: 1 to 3 seconds for an application load balancer in our measurements; we have not measured network load balancers. Old containers keep receiving part of the requests until ECS removes them from the load balancer. Without aninternalHealthCheck, that happens about 50 seconds after the deploy finishes, because ECS counts a new container healthy only after it has run for 40 seconds. With one, it happened 15 to 40 seconds after the new containers turned healthy. - First deploy with Stacktape v4 (
http-api-gateway): v4 protects old containers behind API Gateway while they shut down (see below). The first deployment that adds this protection still retires old containers without it. Keep an application shutdown delay for that one deployment, or deploy in a maintenance window. - With gradual deployments: the deploy follows the CodeDeploy traffic-shifting strategy
instead, and containers keep a 5-second drain and a 2-second default
stopTimeout.
Stacktape does not check that requests already reach the new containers when a fast deployment finishes; no AWS API shows that moment. The 4 seconds are an allowance for routing to catch up.
Old containers behind API Gateway
With the default http-api-gateway load balancing, API Gateway finds containers through AWS Cloud Map and has no
health check of its own. It sends requests to the containers Cloud Map returns: the healthy ones or, while none is
healthy, all of them. Without an internalHealthCheck, ECS registers a new container as healthy as soon as it starts.
With one, ECS registers it as unhealthy and marks it healthy once the check passes, and Cloud Map applies that change
seconds to a minute later. Once ECS removes the old containers from Cloud Map, it returns only the new ones.
API Gateway can keep routing requests to an old container after ECS removes it from Cloud Map. To cover that, Stacktape
adds a small stp-cloudmap-drain container to tasks behind an HTTP API:
- ECS stops this container first. It waits 35 seconds before ECS signals your application containers, so your app can
then close its server on
SIGTERMand use its ownstopTimeoutto finish in-flight work. - Code-only deploys keep their completion timing: this delay runs in the background and does not add a readiness check. Full CloudFormation deploys, scale-in and deletion take about 36 seconds longer per stopped task; tasks stopped in parallel wait in parallel.
- The delay is 35 seconds. To raise it, use task definition
overridesto change the drain container's command and raise itsStopTimeoutabove the new delay. - The container is non-essential. If it exits unexpectedly, your app keeps running but loses this protection.
- It uses a digest-pinned BusyBox image that Stacktape copies once into the stack's private ECR repository, for both amd64 and arm64, without Docker. Later deploys reuse the cached images, and task starts pull only from private ECR.
- The privileged Console connection role already allows this copy. Restricted deployer roles need
ecr:BatchGetImage,ecr:BatchCheckLayerAvailability,ecr:InitiateLayerUpload,ecr:UploadLayerPart,ecr:CompleteLayerUploadandecr:PutImageon the stack's deployment repository, even when all application images are prebuilt. - Upgrade the CLI for your whole team and on Console runners before you deploy with this helper. Older CLIs can delete its cached images during image retention.
Side containers
A Stacktape web service can run helper containers alongside the main container through sideContainers. Each side container has a containerType of either run-on-init or always-running. Use run-on-init for setup work such as database migrations — the helper must exit with code 0 before the main container starts. Use always-running for agents or companion processes that run for the entire task lifecycle; they can reach the main container via localhost, and if they crash, the whole task fails.
The example above shows a run-on-init side container for migrations. For an always-running side container such as a log forwarder or monitoring agent, set containerType: 'always-running' instead — the container runs for the entire task lifetime and shares the network namespace (localhost) with the main container. Choose run-on-init when the helper is a one-time setup step; choose always-running when the helper must stay up alongside the main process.
Use the built-in web service side-container model when one main public container owns the endpoint and helpers are secondary. Use a multi-container-workload instead when you need a workload model centered on multiple containers with their own integrations and lifecycle configuration.
EFS storage
volumeMounts, rootDirectory and readOnly configure the deployed ECS task. stacktape dev does not automatically mount or emulate EFS volumes. Use explicit local test storage when needed, and verify EFS persistence, directory isolation and read-only enforcement in a deployed stage.
A Stacktape web service can mount an EFS filesystem when data must survive container replacement. EFS is useful for shared uploads, generated files, or model artifacts that are too large or slow to fetch repeatedly; skip EFS when data can live in S3, a database, memory, or the container filesystem.
mountPath is the absolute path where the EFS volume appears inside the container. rootDirectory limits the mounted view to a subdirectory of the filesystem. EFS adds network storage cost and latency, so prefer object storage for files that do not need a mounted filesystem interface.
Gradual deployments
A Stacktape web service can shift traffic gradually during deployment with the deployment property, but only when loadBalancing.type is application-load-balancer. Use gradual deployments for production services where a bad release should reach only a small portion of traffic before full rollout; skip them for low-risk stages where faster deployment matters more.
The deployment configuration supports canary, linear, or all-at-once gradual traffic shifting strategies. Configure a strategy through the deployment property to control how traffic shifts between the old and new version during a deploy. See gradual deployments for the full list of strategies and their behavior.
The deployment property enables gradual traffic shifting when loadBalancing.type is application-load-balancer. Configure specific strategy fields (canary, linear, or all-at-once) as documented in gradual deployments.
Private subnets
A Stacktape web service runs in the default networking mode unless you set usePrivateSubnetsWithNAT: true. Private subnets with NAT remove the container's public IP and route outbound traffic through the stack's NAT, which is useful when external APIs require fixed allowlisted IP addresses. The flag requires stackConfig.nat, which picks the NAT: ec2 or ha-ec2 (small Stacktape-managed instances, about $7 a month per zone) or gateway (managed NAT Gateways, about $32 a month per zone plus a per-GB fee); see VPC and networking.
With ha-ec2 and gateway, stackConfig.nat.availabilityZones controls whether two or three availability zones get their own NAT; the default is 2. NAT Gateways add approximately ~$32/month each plus data processing fees, so keep the default networking mode unless static outbound IPs or private subnet placement are real requirements.
Logging
Container output (stdout and stderr) is automatically sent to CloudWatch Logs and retained for 90 days by default. The logging property controls the logging configuration. Use log forwarding when logs need to reach external observability tools.
Logs are a core operating path for always-on containers. Keep application logs structured enough to debug request failures, startup errors, and health-check failures, then view them through the Stacktape Console or the stacktape logs CLI command.
Remote sessions
A Stacktape web service can enable interactive container access by setting enableRemoteSessions to true (defaults to false). Remote sessions provide interactive shell access through the stacktape container shell CLI command. Enabling this feature adds a small SSM agent that uses minimal CPU and memory.
Keep remote sessions disabled by default for routine services and enable them deliberately when production debugging requires shell access. Prefer logs, metrics, and repeatable diagnostic scripts first; an interactive session is strongest for inspecting a live process, filesystem state, or network reachability that cannot be reproduced locally.
Web Service FAQ
Does a Stacktape web service scale to zero?
No. A Stacktape web service is always-on container compute, and Fargate bills while tasks are running, so minInstances is your baseline cost even during idle periods. Use a Lambda function when scale-to-zero billing is more important than keeping a container warm.
Which load balancing mode should I choose?
Use the default http-api-gateway mode for most HTTP APIs and web apps. Choose application-load-balancer for WebSockets, gradual deployments, top-level useFirewall, or high steady request volume. Choose network-load-balancer only for TCP/TLS protocols that are not ordinary HTTP; see Application Load Balancer and Network Load Balancer.
Why isn't my custom domain working?
The most common cause is missing DNS setup: customDomains only auto-creates the DNS record and TLS certificate when the domain is already a Route53 hosted zone in your AWS account, with the registrar's nameservers pointing at that zone. If you manage DNS elsewhere, set disableDnsRecordCreation: true and point the record yourself, or supply your own ACM certificate via customCertificateArn. See custom domains.
Why are my cors settings being ignored?
The cors property only takes effect with the default http-api-gateway load balancing mode; it does nothing under application-load-balancer or network-load-balancer. It also overrides CORS headers your application returns, so for route-specific behavior prefer handling CORS in your application code instead.
How much does an ECS Fargate web service cost?
Fargate bills by allocated vCPU and memory for each running task, so idle web service instances still cost money. The provided Stacktape pricing source lists approximate us-east-1 monthly components starting around ~$7.29 per 0.25 vCPU plus ~$1.60 per 512 MB memory, with ARM tasks about 20% cheaper. For cost monitoring, see Managing Costs.
Web service vs Lambda function: which should I use?
Use a web service when your application is already a long-running container, needs stable always-on latency, uses protocols or libraries better suited to servers, or needs container-level control. Use a Lambda function for event-driven work, sporadic traffic, or workloads where scale-to-zero billing is the main goal. If the container should not be reachable from the internet at all, use a private-service instead.
How do I run database migrations for a web service?
Use a sideContainers entry with containerType: 'run-on-init' when the migration must complete before the main container starts. For more complex multi-container lifecycle and traffic routing, use a multi-container-workload. For broader deployment automation, see deployment scripts and hooks.
Can I protect a web service with AWS WAF?
Yes, but the attachment path matters. Top-level useFirewall attaches a regional firewall directly to the web service's Application Load Balancer and requires loadBalancing.type: 'application-load-balancer'; CDN protection is configured separately through cdn.useFirewall with a CDN-scoped firewall. See web application firewall.
API Reference
WebServicePropsReferenceable parameters
The following parameters can be easily referenced using $ResourceParam directive directive.
To learn more about referencing parameters, refer to referencing parameters.
Web service default domain name
- Usage:
$ResourceParam('<<resource-name>>', 'domain')
Web service default URL
- Usage:
$ResourceParam('<<resource-name>>', 'url')
Comma-separated list of custom domain names assigned to the Web Service (only available if you use custom domain names)
- Usage:
$ResourceParam('<<resource-name>>', 'customDomains')
Comma-separated list of custom domain name URLs (only available if you use custom domain names)
- Usage:
$ResourceParam('<<resource-name>>', 'customDomainUrls')
Default domain of the CDN distribution (only available if you DO NOT configure custom domain names for the CDN).
- Usage:
$ResourceParam('<<resource-name>>', 'cdnDomain')
Default url of the CDN distribution (only available if you DO NOT configure custom domain names for the CDN).
- Usage:
$ResourceParam('<<resource-name>>', 'cdnUrl')
Comma-separated list of custom domain names assigned to the CDN (only available if you configure custom domain names for the CDN).
- Usage:
$ResourceParam('<<resource-name>>', 'cdnCustomDomains')
Comma-separated list of custom domain name URLs of the CDN (only available if you configure custom domain names for the CDN).
- Usage:
$ResourceParam('<<resource-name>>', 'cdnCustomDomainUrls')
In-place code swap
Set properties.codeSwap: true to opt into in-place code swaps. It supports Node.js and Python on x86 Fargate behind an HTTP API or an application load balancer within the ten-task cap, including production. Old and new processes share memory; a sudden increase can fail in-flight requests. Unsupported services and failed memory screens use image deploys.