# Lambda MicroVMs

Source: /aws/services/lambda-microvms/

## Introduction

[Lambda MicroVMs](https://docs.aws.amazon.com/lambda/latest/dg/lambda-microvms-guide.html) run isolated, long-lived environments from images that you build with a Dockerfile.

LocalStack builds MicroVM images, runs MicroVMs as local Docker containers, and serves their endpoints.
It also supports the `AWS::Lambda::MicrovmImage` [CloudFormation](/aws/services/cloudformation/) resource type.
The supported APIs are available on our [API Coverage section](#api-coverage), which provides information on the extent of Lambda MicroVMs' integration with LocalStack.

## Getting started

This guide is designed for users new to Lambda MicroVMs and assumes basic knowledge of the AWS CLI and our [`lstk aws`](/aws/developer-tools/running-localstack/lstk/cloud-and-iac-commands/#aws) command.

Start your LocalStack container using your preferred method.
LocalStack builds MicroVM images and runs MicroVMs with Docker, so LocalStack needs access to the Docker socket.
We will build an image of a small Python web server that serves a message stored in S3, run a MicroVM from it, and call it with curl.

### Create the application

A MicroVM image is built from a ZIP file that contains a `Dockerfile` and your application.
By default, the endpoint forwards requests to port `8080`.

Create a file called `app.py` with the following code.
The root path answers with a greeting, and `/message` returns the content of `message.txt` from S3:

```python title="app.py" showLineNumbers
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

import boto3

s3 = boto3.client("s3")


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/message":
            obj = s3.get_object(Bucket=os.environ["BUCKET_NAME"], Key="message.txt")
            body = obj["Body"].read()
        else:
            body = f"Hello from MicroVM image {os.environ['AWS_LAMBDA_MICROVM_IMAGE_NAME']}\n".encode()
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)


ThreadingHTTPServer(("0.0.0.0", 8080), Handler).serve_forever()
```

Create a `Dockerfile` next to it:

```dockerfile title="Dockerfile"
FROM public.ecr.aws/docker/library/python:3.12-slim
RUN pip install --no-cache-dir boto3
WORKDIR /app
COPY app.py .
EXPOSE 8080
CMD ["python", "-u", "app.py"]
```

Package both files into a ZIP file:

```bash
zip app.zip Dockerfile app.py
```

### Upload the code and the message to S3

Create a bucket and upload the ZIP file and the message the application serves:

```bash
lstk aws s3 mb s3://microvm-code
lstk aws s3 cp app.zip s3://microvm-code/app.zip
echo "Hello from LocalStack S3!" > message.txt
lstk aws s3 cp message.txt s3://microvm-code/message.txt
```

```bash title="Output"
make_bucket: microvm-code
upload: ./app.zip to s3://microvm-code/app.zip
upload: ./message.txt to s3://microvm-code/message.txt
```

### Create the roles

Lambda uses a build role to read the code and write build logs, and an execution role whose credentials the MicroVM's application runs with.
Create a file called `trust-policy.json` that lets Lambda assume both roles:

```json title="trust-policy.json"
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {"Service": "lambda.amazonaws.com"},
      "Action": ["sts:AssumeRole", "sts:TagSession"]
    }
  ]
}
```

Create a file called `build-policy.json` for the build role:

```json title="build-policy.json"
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::microvm-code/app.zip"
    },
    {
      "Effect": "Allow",
      "Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
      "Resource": "*"
    }
  ]
}
```

Create a file called `execution-policy.json` for the execution role, which also allows the application to read `message.txt`:

```json title="execution-policy.json"
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::microvm-code/message.txt"
    },
    {
      "Effect": "Allow",
      "Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
      "Resource": "*"
    }
  ]
}
```

Then create the roles and attach the policies:

```bash
lstk aws iam create-role \
    --role-name microvm-build-role \
    --assume-role-policy-document file://trust-policy.json
lstk aws iam put-role-policy \
    --role-name microvm-build-role \
    --policy-name build \
    --policy-document file://build-policy.json
lstk aws iam create-role \
    --role-name microvm-execution-role \
    --assume-role-policy-document file://trust-policy.json
lstk aws iam put-role-policy \
    --role-name microvm-execution-role \
    --policy-name run \
    --policy-document file://execution-policy.json
```

The roles' policies only restrict the build and the application when you enable [`ENFORCE_IAM`](/aws/customization/configuration-options/#iam).

### Create the MicroVM image

Create the image with `create-microvm-image`.
It builds on the Lambda-managed `al2023-1` base image, which you can find with `list-managed-microvm-images`, and passes the bucket name to the application as an environment variable:

```bash
lstk aws lambda-microvms create-microvm-image \
    --name my-app \
    --base-image-arn arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1 \
    --build-role-arn arn:aws:iam::000000000000:role/microvm-build-role \
    --code-artifact uri=s3://microvm-code/app.zip \
    --environment-variables BUCKET_NAME=microvm-code \
    --query '[imageArn,state]'
```

```bash title="Output"
[
    "arn:aws:lambda:us-east-1:000000000000:microvm-image:my-app",
    "CREATING"
]
```

The first version, `1.0`, builds in the background.
Repeat the following command until the image's state is `CREATED`:

```bash
lstk aws lambda-microvms get-microvm-image \
    --image-identifier arn:aws:lambda:us-east-1:000000000000:microvm-image:my-app \
    --query state
```

```bash title="Output"
"CREATED"
```

If the state is `CREATE_FAILED`, `get-microvm-image-version` shows the reason in `stateReason`, and the build output is in the image's [log group](#logs).

### Run a MicroVM

Run a MicroVM from the image's latest active version with the execution role:

```bash
lstk aws lambda-microvms run-microvm \
    --image-identifier arn:aws:lambda:us-east-1:000000000000:microvm-image:my-app \
    --execution-role-arn arn:aws:iam::000000000000:role/microvm-execution-role
```

```bash title="Output"
{
    "microvmId": "microvm-8ae51660-ca4b-45de-8e41-f87ce5f7269c",
    "state": "PENDING",
    "endpoint": "cbc0073bae2b411a9d721243516df9e2-lambda-microvm-us-east-1.localhost.localstack.cloud:4566",
    "imageArn": "arn:aws:lambda:us-east-1:000000000000:microvm-image:my-app",
    "imageVersion": "1.0",
    "executionRoleArn": "arn:aws:iam::000000000000:role/microvm-execution-role",
    "maximumDurationInSeconds": 28800,
    "startedAt": "2026-11-05T10:40:41.381209+02:00",
    "ingressNetworkConnectors": [
        "arn:aws:lambda:us-east-1:aws:network-connector:aws-network-connector:HTTP_INGRESS"
    ],
    "egressNetworkConnectors": [
        "arn:aws:lambda:us-east-1:aws:network-connector:aws-network-connector:INTERNET_EGRESS"
    ]
}
```

The MicroVM starts in the `PENDING` state.
Check that it is `RUNNING`:

```bash
lstk aws lambda-microvms get-microvm \
    --microvm-identifier microvm-8ae51660-ca4b-45de-8e41-f87ce5f7269c \
    --query state
```

```bash title="Output"
"RUNNING"
```

### Call the endpoint

Every request to the endpoint needs an auth token that allows the port it is sent to.
Create a token that allows port `8080` for 60 minutes, and store it in a shell variable:

```bash
TOKEN=$(lstk aws lambda-microvms create-microvm-auth-token \
    --microvm-identifier microvm-8ae51660-ca4b-45de-8e41-f87ce5f7269c \
    --expiration-in-minutes 60 \
    --allowed-ports port=8080 \
    --query 'authToken."X-aws-proxy-auth"' \
    --output text)
```

Send the token in the `X-aws-proxy-auth` header:

```bash
curl -H "X-aws-proxy-auth: $TOKEN" \
    http://cbc0073bae2b411a9d721243516df9e2-lambda-microvm-us-east-1.localhost.localstack.cloud:4566/
curl -H "X-aws-proxy-auth: $TOKEN" \
    http://cbc0073bae2b411a9d721243516df9e2-lambda-microvm-us-east-1.localhost.localstack.cloud:4566/message
```

```bash title="Output"
Hello from MicroVM image my-app
Hello from LocalStack S3!
```

The application's S3 client needed no endpoint, region or credentials configuration.
See [Calling AWS services from the application](#calling-aws-services-from-the-application) for how LocalStack wires it up.

### Terminate the MicroVM

Terminate the MicroVM when you no longer need it:

```bash
lstk aws lambda-microvms terminate-microvm \
    --microvm-identifier microvm-8ae51660-ca4b-45de-8e41-f87ce5f7269c
```

## Endpoints

LocalStack serves a MicroVM's endpoint as a single label under `localhost.localstack.cloud`, so the LocalStack certificate covers it:

```text
<id>-lambda-microvm-<region>.localhost.localstack.cloud:<port>
```

Read the endpoint from the `endpoint` field of `run-microvm` or `get-microvm` rather than building it.
The host and port come from [`LOCALSTACK_HOST`](/aws/customization/configuration-options/#core).
The endpoint serves HTTP/1.1, HTTP/2 and WebSocket requests, over HTTP and HTTPS.

### Interactive shell

You can open a shell in a running MicroVM that was started with the `SHELL_INGRESS` ingress connector.
Pass it to `run-microvm` together with `HTTP_INGRESS`, and create a token with `create-microvm-shell-auth-token`:

```bash
lstk aws lambda-microvms run-microvm \
    --image-identifier arn:aws:lambda:us-east-1:000000000000:microvm-image:my-app \
    --ingress-network-connectors \
        arn:aws:lambda:us-east-1:aws:network-connector:aws-network-connector:HTTP_INGRESS \
        arn:aws:lambda:us-east-1:aws:network-connector:aws-network-connector:SHELL_INGRESS \
    --query endpoint

lstk aws lambda-microvms create-microvm-shell-auth-token \
    --microvm-identifier <microvm-id> \
    --expiration-in-minutes 15 \
    --query 'authToken."X-aws-proxy-auth"' \
    --output text
```

Open a WebSocket to the endpoint with the shell token.
The following Python script, which uses the [`websockets`](https://pypi.org/project/websockets/) library, runs one command:

```python title="shell.py" showLineNumbers
import sys

from websockets.sync.client import connect

endpoint, token = sys.argv[1], sys.argv[2]
protocols = ["lambda-microvms", f"lambda-microvms.authentication.{token}"]
with connect(f"wss://{endpoint}/", subprotocols=protocols) as websocket:
    print(websocket.recv())
    websocket.send(b"whoami; exit\n")
    for message in websocket:
        print(message.decode(errors="replace"), end="")
```

```bash title="Output"
{"type":"session_init","session_id":"ca282b7e-38cf-4d18-b802-9a7ad1a9058e"}
root@localhost:/# whoami; exit
root
exit
```

## Suspending and resuming

LocalStack supports `suspend-microvm` and `resume-microvm`, and the idle policy of `run-microvm`, including `autoResumeEnabled`.
A suspended MicroVM's container is paused, so the application keeps its memory and processes.
A request to the endpoint waits up to 60 seconds for its MicroVM to start or resume.

## Resources and capabilities

LocalStack limits the MicroVM's container to one vCPU and 2 GiB of memory for each 512 MiB of the image's `minimumMemoryInMiB`, with no swap.
The number of vCPUs is capped at the number of CPUs of your Docker host.
`--additional-os-capabilities ALL` grants the container all Linux capabilities.

## Networking

MicroVMs accept the Lambda-managed ingress and egress connectors, and [network connectors](/aws/services/lambda/#network-connectors) that you create with `lambda-core`.
MicroVM containers use the LocalStack DNS server, so domains such as `*.localhost.localstack.cloud` resolve to LocalStack from inside the MicroVM.

## Calling AWS services from the application

If you pass `--execution-role-arn` to `run-microvm`, the application runs with the role's credentials.
LocalStack also sets `AWS_DEFAULT_REGION`, and `AWS_ENDPOINT_URL` to the LocalStack endpoint, so AWS SDK calls from your application reach LocalStack without any change to your code.
AWS does not set these variables.
Set the [configuration option](/aws/customization/configuration-options/#lambda-microvms) `LAMBDA_MICROVMS_DISABLE_AWS_ENDPOINT_URL=1` to stop LocalStack from setting `AWS_ENDPOINT_URL`.

## Logs

Build output goes to the image's log group, `/aws/lambda-microvms/<image-name>` unless you set `--logging` on the image.
A MicroVM's output goes to the same log group, in a stream named `<date>[<version>]<microvm-id>`, but only when the MicroVM has an execution role:

```bash
lstk aws logs describe-log-streams \
    --log-group-name /aws/lambda-microvms/my-app \
    --query 'logStreams[].logStreamName'
```

```bash title="Output"
[
    "1.0/96de1332-b9fa-4336-9f5f-efb13381111a",
    "2026/11/05[1.0]microvm-8ae51660-ca4b-45de-8e41-f87ce5f7269c"
]
```

## Persistence

MicroVM images, their versions and tags are restored with [persistence](/aws/developer-tools/snapshots/persistence/) and [Cloud Pods](/aws/developer-tools/snapshots/cloud-pods/).
LocalStack builds a restored version's Docker image again when you next run a MicroVM from it.
MicroVMs are not restored: after a restart, they are `TERMINATED` with the reason `The MicroVM was terminated because LocalStack restarted.`
A build that was in progress fails.

## Current Limitations

- Images are built with your local Docker daemon from your Dockerfile's `FROM` image, for the architecture of your Docker host.
  The Lambda-managed base image is validated but not used, and `ARM_64` is reported.
- The image snapshot only keeps the file system, so each MicroVM starts the application again instead of restoring its memory and processes.
- [Network connectors](/aws/services/lambda/#network-connectors) do not route traffic, and the `NO_INGRESS` connector does not block the endpoint.
- Endpoints use a [LocalStack-specific domain](#endpoints) instead of `*.on.aws`, and do not support gRPC yet.
- Lambda MicroVMs do not work yet when LocalStack runs on [Kubernetes](/aws/customization/kubernetes/).

## API Coverage


### lambda-microvms API coverage

Source service: `lambda-microvms`. 24 of 24 tracked operations are implemented.

Service documentation: /aws/services/lambda-microvms/
License availability: available starting with the Base plan. See /aws/licensing/ for current plan details.

| Operation | Status |
| --- | --- |
| CreateMicrovmAuthToken | Implemented |
| CreateMicrovmImage | Implemented |
| CreateMicrovmShellAuthToken | Implemented |
| DeleteMicrovmImage | Implemented |
| DeleteMicrovmImageVersion | Implemented |
| GetMicrovm | Implemented |
| GetMicrovmImage | Implemented |
| GetMicrovmImageBuild | Implemented |
| GetMicrovmImageVersion | Implemented |
| ListManagedMicrovmImageVersions | Implemented |
| ListManagedMicrovmImages | Implemented |
| ListMicrovmImageBuilds | Implemented |
| ListMicrovmImageVersions | Implemented |
| ListMicrovmImages | Implemented |
| ListMicrovms | Implemented |
| ListTags | Implemented |
| ResumeMicrovm | Implemented |
| RunMicrovm | Implemented |
| SuspendMicrovm | Implemented |
| TagResource | Implemented |
| TerminateMicrovm | Implemented |
| UntagResource | Implemented |
| UpdateMicrovmImage | Implemented |
| UpdateMicrovmImageVersion | Implemented |
