AWS Lambda Docker container runtime error: Runtime exited with error: exit status 127

While testing my Lambda using a Docker container, when the Lambda is invoked, I’m getting this runtime error:

Process 17(bootstrap) exited: Runtime exited with error: exit status 127

Process exit status code 127 errors are usually a file not found error. Going back through the Lambda logs, luckily there’s an error telling me I have an error in my shell script:

/var/task/test.sh: line 5: output: command not found

Quick and easy fix.

Using Serverless Framework to build and deploy Docker images for AWS Lambdas

AWS Lambdas can be packaged and deployed using a Docker image, described in the docs here.

Serverless Framework makes building and deploying a Docker based Lambda incredibly simple. If you have a simplest Dockerfile like this (from the docs here):

FROM public.ecr.aws/lambda/nodejs:14

# Assumes your function is named "app.js", and there is a package.json file in the app directory 
COPY app.js package.json  ${LAMBDA_TASK_ROOT}

# Install NPM dependencies for function
RUN npm install

# Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)
CMD [ "app.handler" ] 

The handler to be packaged in this image is this simplest hello world function:

exports.handler =  async function(event, context) {
    console.log("EVENT: \n" + JSON.stringify(event, null, 2))
    return "hello!"
  }

To define a Lambda using this image, with Serverless define an ECR section like this to define your image, which will get built using the above Dockerfile in the same folder:

service: lambda-container-1

provider:
  name: aws
  ecr:
    images:
      lambda-container-example:
        path: ./

functions:
  hello:
    image:
      name: lambda-container-example

Run ‘serverless deploy’ and it builds the image, uploads to ECR, and deploys the Lambda all for you.

After deploying, on first test I got this error:

  "errorMessage": "RequestId: 58fe500f-26ee-44ba-b6a9-6079b6ff2896 Error: fork/exec /lambda-entrypoint.sh: exec format error",
  "errorType": "Runtime.InvalidEntrypoint"

The key part of this error is this “exec format error”. I’m building and deploying this from my M1 MacBook Pro, which is Apple’s arm64, not x64.

If we look in the AWS Console for this lambda, on the first page under Image you’ll see the Lambda runtime architecture:

Updating the serverless.yml to include ‘architecture: arm64’, redeploy and now the architecture is arm64:

Invoking with ‘serverless invoke –function hello’ and now it successfully runs!

Deploying Docker containers to AWS ECS Fargate

The interesting feature of AWS ECS Fargate is that it’s ‘serverless for containers’. Serverless broadly means you don’t need to be concerned with the provisioning and maintenance of the servers or compute that are running your code. With Fargate, you don’t have to provision compute for your Docker Containers, AWS manages the compute for you.

If you’re working with Docker containers, AWS have multiple runtime options, each with their own pros and cons:

  • running Docker on your own EC2 instances – the roll your own approach, you provision instances and manage everything yourself
  • AWS ECS with EC2 launch type – you still need to provision a pool of available EC2 instances on which AWS will run your containers
  • AWS EKS – managed Kubernetes
  • AWS ECS with Fargate launch type – you don’t need to provision any compute (e.g. EC2), AWS manages the compute for you

I’m taking a look at AWS ECS Fargate to see what it takes to deploy a Docker container.

An ECS cluster needs a VPC in which your container instances will run, with at least 1 public or private subnet. Steps to create a new VPC with subnets is covered here.

Following these steps from the VPC section in ECS tutorials using the AWS Console I created:

  • an Elastic IP to associate with my cluster for public access
  • a new VPC with 1 private subnet and 1 public subnet

I created these with the VPC Wizard using this option:

Apparently your public subnet doesn’t get assigned a public IP by default, so follow these steps in the guide to change this default behavior:

When you select your public subnet, this option is under Actions here:

Select this option:

My public subnet was created in AZ us-west-2a and my private subnet is also in the same AZ. The guide recommends creating 1 additional public and private subnets in a different AZ high for availability.

To create a ECS Fargate cluster you can use the AWS CLI like this:

aws ecs create-cluster --cluster-name your-fargate-cluster-name

This will return some stats about your newly created cluster, like:

"clusterName": "fargate-cluster1",
"status": "ACTIVE",
"registeredContainerInstancesCount": 0,
"runningTasksCount": 0,
"pendingTasksCount": 0,
"activeServicesCount": 0,
"statistics": [],
"tags": [],
"settings": [
{
"name": "containerInsights",
"value": "disabled"
}
],
"capacityProviders": [],
"defaultCapacityProviderStrategy": []

However, I’m not sure at this point how to configure the new cluster to specify the VPC and subnets I just created, so for my first cluster I’m going to use the ECS wizard in the AWS Console first, and then come back to the CLI later.

Using the wizard I selected the Networking Only option with Fargate:

I don’t need to select the ‘Create VPC’ option because I’ve already created one:

Turns out there aren’t any options to associate the VPC at this point, the tasks are associated to your VPC and subnets when you create them next. So using the CLI step earlier would create the cluster exactly the same.

You need to define an ECS task definition that defines the task that will run on the ECS cluster. Following the tutorial here, the example JSON file provided as an example looks like this:

{
"family": "sample-fargate",
"networkMode": "awsvpc",
"containerDefinitions": [
{
"name": "fargate-app",
"image": "httpd:2.4",
"portMappings": [
{
"containerPort": 80,
"hostPort": 80,
"protocol": "tcp"
}
],
"essential": true,
"entryPoint": [
"sh",
"-c"
],
"command": [
"/bin/sh -c \"echo ' Amazon ECS Sample App
body {margin-top: 40px; background-color: #333;}
Amazon ECS Sample App
Congratulations!
Your application is now running on a container in Amazon ECS.
' > /usr/local/apache2/htdocs/index.html && httpd-foreground\""
]
}
],
"requiresCompatibilities": [
"FARGATE"
],
"cpu": "256",
"memory": "512"
}

Since we’re deploying a Docker container, we need to specify a Docker image to pull some somewhere. This example provides the name of a Docker container to pull from Docker Hub, in this case httpd:2.4. To. deploy your own apps, you configure your own dockerfile for your app, and publish it to a Docker repo like Docker Hub, or AWS ECR.

Register this task definition with:

aws ecs register-task-definition --cli-input-json file://task-def.json

When –cli-input-json reads your config file, it will open is whatever is your default editor in your shell. On my Mac in zsh it appears to open the file in vim with a ‘:’ prompt at the bottom of the screen, and pressing ‘q’ quits the editor and continues registering the Task Def.

You can list registered Task Definitions with:

aws ecs list-task-definitions

By default, your ECS service will only have a private IP, and would typically be exposed publicly via an ELB. You can configure the task to get allocated it’s own public IP by adding this config:

"networkConfiguration": {
"awsvpcConfiguration": {
"assignPublicIp": "ENABLED",
"securityGroups": [ "sg-12345678" ],
"subnets": [ "subnet-12345678" ]
}
}

This is where we we specify the subnets that were created earlier. I’m going to publicly expose this container, so I’m associating it with the 2 public subnets I created (added to the above config snippet).

I also need a Security Group for the config, so I’ll create that too and allow incoming traffic on port 80.

It’s not obvious from the docs where this NetworkConfiguration section gets specified, but it doesn’t go in the Task Definition json, it gets passed when you create the Service using the Task Definition.

To create a Service, use this cli command:

aws ecs create-service --cluster fargate-cluster --service-name fargate-service --task-definition sample-fargate:1 --desired-count 1 --launch-type "FARGATE" --network-configuration "awsvpcConfiguration={subnets=[subnet-abcd1234],securityGroups=[sg-abcd1234],assignPublicIp=ENABLED}"

Using this command to plug in the subnet ids and Security Group id, from the ECS Console you’ll now see you have service running! If you drill down to the task you can find the assigned public IP. Hit the IP to call the service! Since we’re running an httpd container with a sample web page, we see:

Awesome, up and running!