Multi-Container workloads



A multi-container workload is a compute resource that runs one or more containers continuously. Unlike functions and batch jobs, which are event-driven, container workloads are designed for long-running applications and scale based on CPU and memory usage.

Like other Stacktape compute resources, container workloads are serverless, meaning you don't need to manage the underlying infrastructure. You can provide your container image by building it from source code, using a Dockerfile, or pulling a pre-built image.

Workloads run securely within a VPC, and you can expose container ports to the internet using integrations with HTTP API Gateways and Load Balancers.

Under the hood

Stacktape uses AWS Elastic Container Service (ECS) to orchestrate containers. You can run your containers using two launch types:

  • Fargate: A serverless compute engine that runs containers without requiring you to manage servers.
  • EC2 instances: Virtual machines that give you more control over the operating environment.

ECS services are self-healing, automatically replacing any unhealthy container instances. They also provide auto-scaling out of the box.

When to use

If you're unsure which compute resource to use, this table provides a comparison of container-based resources in Stacktape:

Resource typeDescriptionUse-cases
web-servicecontinuously running container with public endpoint and URLpublic APIs, websites
private-servicecontinuously running container with private endpointprivate APIs, services
worker-servicecontinuously running container not accessible from outsidecontinuous processing
multi-container-workloadcustom multi container workload - you can customize accessibility for each containermore complex use-cases requiring customization
batch-jobsimple container job - container is destroyed after job is doneone-off/scheduled processing jobs

Advantages

  • Control over environment: You can run any Docker image or build from your own Dockerfile.
  • Cost-effective for predictable loads: More economical than functions for applications with consistent traffic.
  • Load-balanced and auto-scalable: Automatically scales horizontally based on CPU and memory utilization.
  • High availability: Runs in multiple Availability Zones for resilience.
  • Secure by default: The underlying environment is securely managed by AWS.

Disadvantages

  • Slower scaling: Adding new container instances takes longer than scaling functions.
  • Not fully serverless: Cannot scale to zero, meaning you will always pay for at least one running instance.

Basic usage

import express from 'express';

const app = express();

app.get('/', async (req, res) => {
  res.send({ message: 'Hello' });
});

app.listen(process.env.PORT, () => {
  console.info(`Server running on port ${process.env.PORT}`);
});

Example server container written in Typescript

resources:
  mainGateway:
    type: http-api-gateway
  apiServer:
    type: multi-container-workload
    properties:
      resources:
        cpu: 2
        memory: 2048
      scaling:
        minInstances: 1
        maxInstances: 5
      containers:
        - name: api-container
          packaging:
            type: stacktape-image-buildpack
            properties:
              entryfilePath: src/main.ts
          environment:
            - name: PORT
              value: 3000
          events:
            - type: http-api-gateway
              properties:
                method: '*'
                path: /{proxy+}
                containerPort: 3000
                httpApiGatewayName: mainGateway

Container connected to HTTP API Gateway

Containers

Every workload consists of one or more containers. You can configure the following properties for each container:

ContainerWorkloadContainerAPI referenceParent:ContainerWorkload
nameRequired

Unique container name within this workload.

Type: string

packagingRequired

How to build or specify the container image.

Type: ContainerWorkloadContainerPackaging

events

How this container receives traffic (API Gateway, load balancer, or service-connect).

Type: Array of ContainerWorkloadLoadBalancerIntegration or ContainerWorkloadHttpApiIntegration or ContainerWorkloadInternalIntegration or ContainerWorkloadServiceConnectIntegration or ContainerWorkloadNetworkLoadBalancerIntegration

loadBalancerHealthCheck

Load balancer health check settings. Only applies when integrated with an ALB or NLB.

Type: LoadBalancerHealthCheck

essential

If true (default), the entire workload restarts when this container fails.

Type: boolean

logging

Container logging (stdout/stderr). Sent to CloudWatch, viewable with stacktape logs.

Type: ContainerWorkloadContainerLogging

dependsOn

Start this container only after the listed containers reach a specific state.

Type: Array of ContainerDependency

E.g., wait for a database sidecar to be HEALTHY before starting the app container.

environment

Environment variables injected at runtime. Use $ResourceParam() or $Secret() for dynamic values.

Type: Array of EnvironmentVar

internalHealthCheck

Command-based health check. If it fails on an essential container, the workload instance is replaced.

Type: ContainerHealthCheck

stopTimeoutDefault: 2

Seconds to wait after SIGTERM before SIGKILL (2-120).

Type: number

volumeMounts

Mount EFS volumes for persistent, shared storage across containers.

Type: Array of ContainerEfsMount

Image

You can provide a container image in four ways:

Environment variables

A list of environment variables to pass to the script or command.

Values can be:

environment:
  - name: STATIC_ENV_VAR
    value: my-env-var
  - name: DYNAMICALLY_SET_ENV_VAR
    value: $MyCustomDirective('input-for-my-directive')
  - name: DB_HOST
    value: $ResourceParam('myDatabase', 'host')
  - name: DB_PASSWORD
    value: $Secret('dbSecret.password')
EnvironmentVarAPI referenceParent:ContainerWorkloadContainer
nameRequired

Environment variable name (e.g., DATABASE_URL, API_KEY).

Type: string

valueRequired

Environment variable value. Numbers and booleans are converted to strings.

Type: string or number or boolean

Dependencies between containers

You can define dependencies between containers to control their startup order.

ContainerDependencyAPI referenceParent:ContainerWorkloadContainer
containerNameRequired

The name of the container that this container depends on.

Type: string

conditionRequired

The condition that the dependency container must meet.

Type: string ENUM

Possible values: COMPLETEHEALTHYSTARTSUCCESS

Available conditions:

  • START: The dependency has started.
  • COMPLETE: The dependency has finished executing (regardless of success).
  • SUCCESS: The dependency has finished with an exit code of 0.
  • HEALTHY: The dependency has passed its first health check.

For example, the frontend container will only start after the backend container is running successfully.

resources:
  myApiGateway:
    type: http-api-gateway

  myMultiContainerWorkload:
    type: multi-container-workload
    properties:
      containers:
        - name: frontend-container
          packaging:
            type: stacktape-image-buildpack
            properties:
              entryfilePath: src/client/index.ts
          dependsOn:
            - containerName: backend
              condition: START
          environment:
            - name: PORT
              value: 80
            - name: API_COINTAINER_PORT
              value: 3000
          events:
            - type: http-api-gateway
              properties:
                httpApiGatewayName: myApiGateway
                containerPort: 80
                path: '*'
                method: '*'
        - name: api-container
          packaging:
            type: stacktape-image-buildpack
            properties:
              entryfilePath: src/server/index.ts
          environment:
            - name: PORT
              value: 3000
          events:
            - type: workload-internal
              properties:
                containerPort: 3000
      resources:
        cpu: 2
        memory: 2048

Healthcheck

A health check monitors the container from within. If an essential container becomes unhealthy, the entire instance is automatically replaced.

ContainerHealthCheckAPI referenceParent:ContainerWorkloadContainer
healthCheckCommandRequired

Command to check health. E.g., ["CMD-SHELL", "curl -f http://localhost/ || exit 1"]. Exit 0 = healthy.

Type: Array of string

intervalSecondsDefault: 30

Seconds between health checks (5-300).

Type: number

timeoutSecondsDefault: 5

Seconds before a check is considered failed (2-60).

Type: number

retriesDefault: 3

Consecutive failures before marking unhealthy (1-10).

Type: number

startPeriodSeconds

Grace period (seconds) before counting failures. Gives the container time to start (0-300).

Type: number


resources:
  myContainerWorkload:
    type: multi-container-workload
    properties:
      containers:
        - name: api-container
          packaging:
            type: stacktape-image-buildpack
            properties:
              entryfilePath: src/index.ts
          internalHealthCheck:
            healthCheckCommand: ['CMD-SHELL', 'curl -f http://localhost/ || exit 1']
            intervalSeconds: 20
            timeoutSeconds: 5
            startPeriodSeconds: 150
            retries: 2
      resources:
        cpu: 2
        memory: 2048

This example uses a shell command to send a curl request every 20 seconds. If the request fails or times out, the health check fails.

Shutdown

When a container instance is shut down, all containers receive a SIGTERM signal, giving them a chance to clean up gracefully. By default, they have 2 seconds before a SIGKILL signal is sent. You can adjust this with the stopTimeout property.

process.on('SIGTERM', () => {
  console.info('Received SIGTERM signal. Cleaning up and exiting process...');

  // Finish any outstanding requests, or close a database connection...

  process.exit(0);
});

Example of cleaning up before container shutdown.

Logging

Any output to stdout or stderr is captured and stored in a CloudWatch log group. You can view logs through the Stacktape Console, the stacktape stack-info command, or by streaming them with the stacktape logs command.

Forwarding logs

You can forward logs to third-party services. See the Log Forwarding documentation for more details.


Events

Events route traffic from an integration to a specified port on your container.

HTTP API event

Forwards requests from an HTTP API Gateway.

ContainerWorkloadHttpApiIntegrationAPI referenceParent:ContainerWorkloadContainer
typeRequired
No description

Type: string "http-api-gateway"

properties.containerPortRequired

The container port that will receive traffic from the API Gateway.

Type: number

properties.httpApiGatewayNameRequired

The name of the HTTP API Gateway.

Type: string

properties.methodRequired

The HTTP method that will trigger this integration.

Type: string ENUM

Possible values: *DELETEGETHEADOPTIONSPATCHPOSTPUT

You can specify an exact method (e.g., GET) or use * to match any method.

properties.pathRequired

The URL path that will trigger this integration.

Type: string

  • Exact path: /users
  • Path with parameter: /users/{id}. The id will be available in event.pathParameters.id.
  • Greedy path: /files/{proxy+}. This will match any path starting with /files/.
properties.authorizer

An authorizer to protect this route.

Type: StpAuthorizer

Unauthorized requests will be rejected with a 401 Unauthorized response.

properties.payloadFormatDefault: '1.0'

The payload format version for the Lambda integration.

Type: string ENUM

Possible values: 1.02.0

For details on the differences between formats, see the AWS documentation.


resources:
  myApiGateway:
    type: http-api-gateway

  myApp:
    type: multi-container-workload
    properties:
      containers:
        - name: api-container
          packaging:
            type: stacktape-image-buildpack
            properties:
              entryfilePath: src/index.ts
          events:
            - type: http-api-gateway
              properties:
                httpApiGatewayName: myApiGateway
                containerPort: 80
                path: '/my-path'
                method: GET
      resources:
        cpu: 2
        memory: 2048

Incoming GET requests to /my-path on myApiGateway are routed to port 80 of the api-container.


Application Load Balancer event

Forwards requests from an Application Load Balancer. This allows for advanced routing based on path, query parameters, headers, and more.

ContainerWorkloadLoadBalancerIntegrationAPI referenceParent:ContainerWorkloadContainer
typeRequired
No description

Type: string "application-load-balancer"

properties.containerPortRequired

The container port that will receive traffic from the load balancer.

Type: number

properties.loadBalancerNameRequired

The name of the Application Load Balancer.

Type: string

This must reference a load balancer defined in your Stacktape configuration.

properties.priorityRequired

The priority of this integration rule.

Type: number

Load balancer rules are evaluated in order from the lowest priority to the highest. The first rule that matches an incoming request will handle it.

properties.listenerPort

The port of the load balancer listener to attach to.

Type: number

You only need to specify this if the load balancer uses custom listeners.

properties.paths

A list of URL paths that will trigger this integration.

Type: Array of string

The request will be routed if its path matches any of the paths in this list. The comparison is case-sensitive and supports * and ? wildcards.

Example: /users, /articles/*

properties.methods

A list of HTTP methods that will trigger this integration.

Type: Array of string

Example: GET, POST, DELETE

properties.hosts

A list of hostnames that will trigger this integration.

Type: Array of string

The hostname is parsed from the Host header of the request. Wildcards (* and ?) are supported.

Example: api.example.com, *.myapp.com

properties.headers

A list of header conditions that the request must match.

Type: Array of LbHeaderCondition

All header conditions must be met for the request to be routed.

properties.queryParams

A list of query parameter conditions that the request must match.

Type: Array of LbQueryParamCondition

All query parameter conditions must be met for the request to be routed.

properties.sourceIps

A list of source IP addresses (in CIDR format) that are allowed to trigger this integration.

Type: Array of string

Note: If the client is behind a proxy, this will be the IP address of the proxy.

LbHeaderConditionAPI referenceParent:ContainerWorkloadLoadBalancerIntegration
headerNameRequired

The name of the HTTP header.

Type: string

valuesRequired

A list of allowed values for the header.

Type: Array of string

The condition is met if the header's value in the incoming request matches any of the values in this list. The comparison is case-insensitive.

LbQueryParamConditionAPI referenceParent:ContainerWorkloadLoadBalancerIntegration
paramNameRequired

The name of the query parameter.

Type: string

valuesRequired

A list of allowed values for the query parameter.

Type: Array of string

The condition is met if the query parameter's value in the incoming request matches any of the values in this list. The comparison is case-insensitive.

resources:
  myLoadBalancer:
    type: application-load-balancer

  myApp:
    type: multi-container-workload
    properties:
      containers:
        - name: api-container
          packaging:
            type: stacktape-image-buildpack
            properties:
              entryfilePath: src/index.ts
          events:
            - type: application-load-balancer
              properties:
                loadBalancerName: myLoadBalancer
                containerPort: 80
                priority: 1
                paths: ['*']
      resources:
        cpu: 2
        memory: 2048

Network Load Balancer event

Forwards traffic from a Network Load Balancer.

ContainerWorkloadNetworkLoadBalancerIntegrationAPI referenceParent:ContainerWorkloadContainer
typeRequired
No description

Type: string "network-load-balancer"

properties.containerPortRequired

The container port that will receive traffic from the load balancer.

Type: number

properties.loadBalancerNameRequired

The name of the Network Load Balancer.

Type: string

This must reference a load balancer defined in your Stacktape configuration.

properties.listenerPortRequired

The port of the listener that will forward traffic to this integration.

Type: number

resources:
  myLoadBalancer:
    type: 'network-load-balancer'
    properties:
      listeners:
        - port: 8080
          protocol: TLS

  myWorkload:
    type: 'multi-container-workload'
    properties:
      containers:
        - name: container1
          packaging:
            type: stacktape-image-buildpack
            properties:
              entryfilePath: containers/ts-container.ts
          events:
            - type: network-load-balancer
              properties:
                loadBalancerName: myLoadBalancer
                listenerPort: 8080
                containerPort: 8080
      resources:
        cpu: 0.25
        memory: 512

Internal port (workload-internal)

Opens a port for communication with other containers within the same workload.

ContainerWorkloadInternalIntegrationAPI referenceParent:ContainerWorkloadContainer
typeRequired
No description

Type: string "workload-internal"

properties.containerPortRequired

The container port to open for internal traffic.

Type: number

resources:
  myApiGateway:
    type: http-api-gateway

  myApp:
    type: multi-container-workload
    properties:
      containers:
        - name: frontend
          packaging:
            type: stacktape-image-buildpack
            properties:
              entryfilePath: src/frontend/index.ts
          dependsOn:
            - containerName: backend
              condition: START
          environment:
            - name: PORT
              value: 80
            - name: BACKEND_PORT
              value: 3000
          events:
            - type: http-api-gateway
              properties:
                httpApiGatewayName: myApiGateway
                containerPort: 80
                path: /my-path
                method: GET
        - name: backend
          packaging:
            type: stacktape-image-buildpack
            properties:
              entryfilePath: src/backend/index.ts
          environment:
            - name: PORT
              value: 3000
          events:
            - type: workload-internal
              properties:
                containerPort: 3000
      resources:
        cpu: 2
        memory: 2048

Private port (service-connect)

Opens a port for communication with other workloads in the same stack.

Other resources in the stack can connect to this service using a URL like protocol://alias:port (e.g., http://my-service:8080). By default, the alias is derived from the resource and container names (e.g., my-resource-my-container).

ContainerWorkloadServiceConnectIntegrationAPI referenceParent:ContainerWorkloadContainer
typeRequired
No description

Type: string "service-connect"

properties.containerPortRequired

The container port to open for service-to-service communication.

Type: number

properties.alias

An alias for this service, used for service discovery.

Type: string

Other resources in the stack can connect to this service using a URL like protocol://alias:port (e.g., http://my-service:8080). By default, the alias is derived from the resource and container names (e.g., my-resource-my-container).

properties.protocol

The protocol used for service-to-service communication.

Type: string ENUM

Possible values: grpchttphttp2

Specifying the protocol allows AWS to capture protocol-specific metrics, such as the number of HTTP 5xx errors.

resources:
  internalService:
    type: multi-container-workload
    properties:
      containers:
        - name: api
          packaging:
            type: stacktape-image-buildpack
            properties:
              entryfilePath: src/private/index.ts
          events:
            - type: service-connect
              properties:
                containerPort: 3000
      resources:
        cpu: 2
        memory: 2048

  publicService:
    type: multi-container-workload
    properties:
      containers:
        - name: api
          packaging:
            type: stacktape-image-buildpack
            properties:
              entryfilePath: src/public/index.ts
      resources:
        cpu: 2
        memory: 2048

Resources

You can specify the CPU, memory, and EC2 instance types for your workload.

  • Fargate (set cpu + memory): Serverless, no servers to manage.
  • EC2 (set instanceTypes): Choose specific instance types for more control or GPU access.

If your workload has multiple containers, the assigned resources are shared between them.

ContainerWorkloadResourcesConfigAPI referenceParent:ContainerWorkload
cpu

VCPUs for the workload (Fargate). Ignored when using instanceTypes.

Type: number ENUM

Possible values: 0.250.5124816

memory

Memory in MB. Must be compatible with the vCPU count on Fargate.

Type: number

Fargate valid combos: 0.25 vCPU → 512-2048 MB, 0.5 → 1024-4096, 1 → 2048-8192, 2 → 4096-16384, 4 → 8192-30720, 8 → 16384-61440, 16 → 32768-122880. For EC2: auto-detected from instance type if omitted.

instanceTypes

EC2 instance types for the workload (e.g., t3.medium, c6g.large). Use instead of cpu/memory.

Type: Array of string

First type in the list is preferred. Instances auto-scale and are refreshed weekly for patching. Tip: specify a single type and omit cpu/memory for optimal sizing.

enableWarmPool

Keep pre-initialized EC2 instances ready for faster scaling. Only works with a single instance type.

Type: boolean

architectureDefault: 'x86_64'

CPU architecture for Fargate. arm64 is ~20% cheaper. Ignored when using instanceTypes.

Type: string ENUM

Possible values: arm64x86_64

Using Fargate

If you omit the instanceTypes property, your workload will run on Fargate.

resources:
  myContainerWorkload:
    type: multi-container-workload
    properties:
      containers:
        - name: api-container
          packaging:
            type: stacktape-image-buildpack
            properties:
              entryfilePath: src/index.ts
      resources:
        cpu: 0.25
        memory: 512

Using EC2 instances

If you specify instanceTypes, your workload will run on EC2 instances.

First type in the list is preferred. Instances auto-scale and are refreshed weekly for patching. Tip: specify a single type and omit cpu/memory for optimal sizing.

resources:
  myContainerWorkload:
    type: multi-container-workload
    properties:
      containers:
        - name: api-container
          packaging:
            type: stacktape-image-buildpack
            properties:
              entryfilePath: src/index.ts
      resources:
        instanceTypes:
          - c5.large

Placing containers on EC2

Stacktape optimizes for 100% utilization of your EC2 instances. If you specify cpu and memory, AWS uses a binpack strategy to place as many workload instances as possible onto the available EC2 instances.

Using warm pool

Enable a warm pool to keep pre-initialized EC2 instances in a stopped state, ready for faster scaling. This is only supported for workloads with a single instance type.

resources:
  myWebService:
    type: web-service
    properties:
      packaging:
        type: stacktape-image-buildpack
        properties:
          entryfilePath: src/index.ts
      resources:
        instanceTypes:
          - c5.large
        enableWarmPool: true

Scaling

Configure the minimum and maximum number of concurrent workload instances and define a scaling policy based on CPU and memory utilization.

ContainerWorkloadScalingAPI referenceParent:ContainerWorkload
minInstancesDefault: 1

Minimum running instances. Set to 0 is not supported — minimum is 1.

Type: number

maxInstancesDefault: 1

Maximum running instances. Traffic is distributed across all instances.

Type: number

scalingPolicy

When to scale: CPU and/or memory utilization targets.

Type: ContainerWorkloadScalingPolicy

Scaling policy

A scaling policy triggers scaling actions when CPU or memory thresholds are crossed. The workload scales out aggressively when metrics are high and scales in more cautiously when they are low.

ContainerWorkloadScalingPolicyAPI referenceParent:ContainerWorkloadScaling
keepAvgCpuUtilizationUnderDefault: 80

Scale out when avg CPU exceeds this %, scale in when it drops below.

Type: number

keepAvgMemoryUtilizationUnderDefault: 80

Scale out when avg memory exceeds this %, scale in when it drops below.

Type: number

resources:
  myContainerWorkload:
    type: multi-container-workload
    properties:
      containers:
        - name: container-1
          packaging:
            type: stacktape-image-buildpack
            properties:
              entryfilePath: src/cont1/index.ts
          events:
            - type: http-api-gateway
              properties:
                httpApiGatewayName: myApiGateway
                containerPort: 80
                method: '*'
                path: '*'
        - name: container-2
          packaging:
            type: stacktape-image-buildpack
            properties:
              entryfilePath: src/cont1/index.ts
          events:
            - type: workload-internal
              properties:
                containerPort: 3000
      resources:
        cpu: 0.5
        memory: 1024
      scaling:
        minInstances: 1
        maxInstances: 5
        scalingPolicy:
          keepAvgMemoryUtilizationUnder: 80
          keepAvgCpuUtilizationUnder: 80

Storage

Each workload instance has 20GB of ephemeral storage, which is shared among all containers within that instance. This storage is deleted when the instance is removed. For persistent storage, use Buckets.

Accessing other resources

By default, workloads cannot access other AWS resources. You must grant permissions using IAM.

Using connectTo

The connectTo property is a simplified way to grant access to other Stacktape-managed resources.

resources:
  photosBucket:
    type: bucket

  myContainerWorkload:
    type: multi-container-workload
    properties:
      containers:
        - name: apiContainer
          packaging:
            type: stacktape-image-buildpack
            properties:
              entryfilePath: sr/index.ts
      connectTo:
        # access to the bucket
        - photosBucket
        # access to AWS SES
        - aws:ses
      resources:
        cpu: 0.25
        memory: 512

List the names of resources this workload needs to communicate with. Stacktape automatically:

  • Grants IAM permissions (e.g., S3 read/write, SQS send/receive)
  • Opens network access (security group rules for databases, Redis)
  • Injects environment variables with connection details: STP_[RESOURCE_NAME]_[PARAM]

Example: connectTo: ["myDatabase", "myBucket"] gives this workload full access to both resources and injects STP_MY_DATABASE_CONNECTION_STRING, STP_MY_BUCKET_NAME, etc.

Using iamRoleStatements

For fine-grained control, you can provide raw IAM role statements.

resources:
  myContainerWorkload:
    type: multi-container-workload
    properties:
      containers:
        - name: apiContainer
          packaging:
            type: stacktape-image-buildpack
            properties:
              entryfilePath: server/index.ts
      iamRoleStatements:
        - Resource:
            - $CfResourceParam('NotificationTopic', 'Arn')
          Effect: 'Allow'
          Action:
            - 'sns:Publish'
      resources:
        cpu: 2
        memory: 2048

cloudformationResources:
  NotificationTopic:
    Type: 'AWS::SNS::Topic'
StpIamRoleStatementAPI referenceParent:ContainerWorkload
ResourceRequired

ARNs of the AWS resources this statement applies to. Use "*" for all resources.

Type: Array of string

Sid

Optional identifier for this statement (for readability).

Type: string

EffectDefault: Allow

Whether to allow or deny the specified actions.

Type: string

Action

AWS actions to allow or deny (e.g., s3:GetObject, sqs:SendMessage).

Type: Array of string

Condition
No description

Type: UNSPECIFIED

Deployment strategies

By default, Stacktape uses a rolling update strategy. You can choose a different strategy using the deployment property.

Gradual traffic shifting (canary/linear) for safe deployments. Requires an ALB integration.

ContainerWorkloadDeploymentConfigAPI referenceParent:ContainerWorkload
strategyRequired

How traffic shifts to the new version during deployment.

Type: string ENUM

Possible values: AllAtOnceCanary10Percent15MinutesCanary10Percent5MinutesLinear10PercentEvery1MinutesLinear10PercentEvery3Minutes

  • Canary10Percent5Minutes: 10% first, then all after 5 min.
  • Canary10Percent15Minutes: 10% first, then all after 15 min.
  • Linear10PercentEvery1Minutes: 10% more every minute.
  • Linear10PercentEvery3Minutes: 10% more every 3 minutes.
  • AllAtOnce: Instant switch.
beforeAllowTrafficFunction

Lambda function to run before traffic shifts to the new version (for validation/smoke tests).

Type: string

afterTrafficShiftFunction

Lambda function to run after all traffic has shifted (for post-deployment checks).

Type: string

testListenerPort

ALB listener port for test traffic. Only needed with beforeAllowTrafficFunction and custom listeners.

Type: number

resources:
  myLoadBalancer:
    type: application-load-balancer

  myApp:
    type: multi-container-workload
    properties:
      containers:
        - name: api-container
          packaging:
            type: stacktape-image-buildpack
            properties:
              entryfilePath: src/index.ts
          events:
            - type: application-load-balancer
              properties:
                loadBalancerName: myLoadBalancer
                containerPort: 80
                priority: 1
                paths: ['*']
      resources:
        cpu: 2
        memory: 2048
      deployment:
        strategy: Canary10Percent5Minutes

Hook functions

You can use hook functions to perform checks during deployment, including sending test traffic to a new version before it receives production traffic.

resources:
  myLoadBalancer:
    type: application-load-balancer

  myApp:
    type: multi-container-workload
    properties:
      containers:
        - name: api-container
          packaging:
            type: stacktape-image-buildpack
            properties:
              entryfilePath: src/index.ts
          events:
            - type: application-load-balancer
              properties:
                loadBalancerName: myLoadBalancer
                containerPort: 80
                priority: 1
                paths: ['*']
      resources:
        cpu: 2
        memory: 2048
      deployment:
        strategy: Canary10Percent5Minutes
        afterTrafficShiftFunction: validateDeployment

  validateDeployment:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: src/validate-deployment.ts
import { CodeDeployClient, PutLifecycleEventHookExecutionStatusCommand } from '@aws-sdk/client-codedeploy';

const client = new CodeDeployClient({});

export default async (event) => {
  // read DeploymentId and LifecycleEventHookExecutionId from payload
  const { DeploymentId, LifecycleEventHookExecutionId } = event;

  // performing validations here

  await client.send(
    new PutLifecycleEventHookExecutionStatusCommand({
      deploymentId: DeploymentId,
      lifecycleEventHookExecutionId: LifecycleEventHookExecutionId,
      status: 'Succeeded' // status can be 'Succeeded' or 'Failed'
    })
  );
};

Default VPC connection

Container workloads are connected to the default VPC of your stack by default. This allows them to communicate with other VPC-enabled resources without extra configuration.

Referenceable parameters

Currently, no parameters can be referenced.

Pricing

You are charged for:

  • Virtual CPU per hour
  • Memory per hour

Pricing is rounded to the nearest second with a one-minute minimum. For details, see the Fargate pricing page.

API reference

ContainerWorkloadAPI reference
typeRequired
No description

Type: string "multi-container-workload"

properties.containersRequired

Containers in this workload. They share compute resources and scale together.

Type: Array of ContainerWorkloadContainer

properties.resourcesRequired

CPU, memory, and compute engine (Fargate or EC2).

Type: ContainerWorkloadResourcesConfig

  • Fargate (set cpu + memory): Serverless, no servers to manage.
  • EC2 (set instanceTypes): Choose specific instance types for more control or GPU access.
properties.scaling

Auto-scaling: how many instances and when to add/remove them.

Type: ContainerWorkloadScaling

properties.deployment

Gradual traffic shifting (canary/linear) for safe deployments. Requires an ALB integration.

Type: ContainerWorkloadDeploymentConfig

properties.enableRemoteSessions

Enable stacktape container:session for interactive shell access to running containers.

Type: boolean

properties.usePrivateSubnetsWithNAT

Run in private subnets with a NAT Gateway for outbound internet. Gives you a static public IP.

Type: boolean

Useful for IP whitelisting with third-party APIs. NAT Gateway costs ~$32/month per AZ + data processing fees.

properties.connectTo

Give this resource access to other resources in your stack.

Type: Array of string

List the names of resources this workload needs to communicate with. Stacktape automatically:

  • Grants IAM permissions (e.g., S3 read/write, SQS send/receive)
  • Opens network access (security group rules for databases, Redis)
  • Injects environment variables with connection details: STP_[RESOURCE_NAME]_[PARAM]

Example: connectTo: ["myDatabase", "myBucket"] gives this workload full access to both resources and injects STP_MY_DATABASE_CONNECTION_STRING, STP_MY_BUCKET_NAME, etc.

properties.iamRoleStatements

Raw IAM policy statements for permissions not covered by connectTo.

Type: Array of StpIamRoleStatement

Added as a separate policy alongside auto-generated permissions. Use this for accessing AWS services directly (e.g., Rekognition, Textract, Bedrock).

overrides

Escape hatch to modify the underlying CloudFormation resources Stacktape creates.

Type: Object

Use dot-notation paths to override specific properties on any child resource. Find resource logical IDs with stacktape stack-info --detailed.

overrides:
  MyDbInstance:
    Properties.StorageEncrypted: true
CognitoAuthorizerAPI reference
typeRequired

Cognito JWT authorizer

Type: string "cognito"

Configures an HTTP API authorizer that validates JSON Web Tokens (JWTs) issued by a Cognito user pool. This is the simplest way to protect routes when your users sign in via user-auth-pool.

Stacktape turns this into an API Gateway v2 authorizer of type JWT that checks the token's issuer and audience.

properties.userPoolNameRequired

Name of the user pool to protect the API

Type: string

The Stacktape name of the user-auth-pool resource whose tokens should be accepted by this HTTP API authorizer. Stacktape uses this to:

  • Set the expected audience to the user pool client ID.
  • Build the expected issuer URL based on the user pool and AWS region.

In practice this means only JWTs issued by this pool (and its client) will be considered valid.

properties.identitySources

Where to read the JWT from in the request

Type: Array of string

A list of identity sources that tell API Gateway where to look for the bearer token, using the $request.* syntax from API Gateway (for example '$request.header.Authorization').

If you omit this, Stacktape defaults to reading the token from the Authorization HTTP header, using a JWT authorizer as described in the API Gateway v2 authorizer docs (AWS::ApiGatewayV2::Authorizer).

LambdaAuthorizerAPI reference
typeRequired

Lambda-based HTTP API authorizer

Type: string "lambda"

Configures an API Gateway request authorizer that runs a Lambda function to decide whether a request is allowed. This is useful when your authorization logic can't be expressed as simple JWT validation – for example when you check API keys, look up permissions in a database, or integrate with a non-JWT identity system.

Stacktape creates an AWS::ApiGatewayV2::Authorizer of type REQUEST and wires it up to your Lambda.

properties.functionNameRequired

Name of the authorizer function

Type: string

The Stacktape name of a function resource that should run for each authorized request. API Gateway calls this Lambda, passes request details, and uses its response to allow or deny access.

properties.iamResponse

Use IAM-style (v1) authorizer responses

Type: boolean

  • If true, your Lambda must return a full IAM policy document (the "v1" format).
  • If false or omitted, Stacktape enables simple responses (the HTTP API v2 payload format) so your Lambda can return a small JSON object with an isAuthorized flag and optional context.

This flag is wired to EnableSimpleResponses on the underlying AWS::ApiGatewayV2::Authorizer.

properties.identitySources

Where to read identity data from

Type: Array of string

A list of request fields API Gateway should pass into your Lambda authorizer (for example headers, query parameters, or stage variables) using the $request.* syntax.

When left empty, no specific identity sources are configured and your Lambda must inspect the incoming event directly.

properties.cacheResultSeconds

Cache authorizer results

Type: number

Number of seconds API Gateway should cache the result of the Lambda authorizer for a given identity. While cached, repeated requests skip calling your authorizer function and reuse the previous result.

This value is applied to AuthorizerResultTtlInSeconds. If omitted, Stacktape sets it to 0 (no caching).

StpIamRoleStatementAPI referenceParent:ContainerWorkload
ResourceRequired

ARNs of the AWS resources this statement applies to. Use "*" for all resources.

Type: Array of string

Sid

Optional identifier for this statement (for readability).

Type: string

EffectDefault: Allow

Whether to allow or deny the specified actions.

Type: string

Action

AWS actions to allow or deny (e.g., s3:GetObject, sqs:SendMessage).

Type: Array of string

Condition
No description

Type: UNSPECIFIED