kloia Blog

LocalStack: AWS On Your Laptop

Written by Cem Altuner | Jan 13, 2022 11:27:16 AM

LocalStack is a cloud application development tool that provides an easy-to-use test/mock system. It creates a testing environment on your local computer that emulates the AWS cloud environment in terms of functionality and APIs.

LocalStack's primary objective is to assist you in speeding up various procedures, simplifying testing, and saving money on development testing. For example, consider the time it takes to spin up an EC2 instance on Amazon Web Services (AWS). It can take a few minutes, but it can take 15 minutes or more to spin up an Elastic Kubernetes Service (EKS). That is acceptable for production environments, but this amount of time may be excessive when it comes to testing. Also, while you are just getting started and testing things out, these procedures can lead to high costs.

It is possible to run Lambda functions, create DynamoDB tables, ECS containers, and more, such as putting your application behind an API Gateway with LocalStack. All of these functionalities are powered by your local machine without ever talking to the cloud.

This blog post includes a Serverless Demo, and code samples can be found in this github repository.

LocalStack has three different customer usage tier options: Community Edition, Pro, and Enterprise. Each of the usage tiers has its available services and features. Pro and Enterprise options require payment, but the Community Edition option is free for personal usage. 

I am going to use the Community Edition option for this blog post. 

The diagram below depicts the various usage tiers (Open Source, Pro, and Enterprise) and the capabilities available in each. And also, you can check the complete list of features from this link here.

Integration with LocalStack

LocalStack is compatible with a wide range of cloud development tools. There are numerous aspects to cloud development, and there is a large ecosystem of tools to handle them all. LocalStack allows you to execute your process entirely on your local workstation, whether you're using Infrastructure-as-Code (IaC) to manage your AWS infrastructure or developing apps with AWS SDKs like boto. LocalStack is compatible with a wide range of cloud development tools. I am going to use the Serverless Framework for this blog post.

Get LocalStack Up and Running

In this section of this blog post, you will see how a simple serverless application can be deployed using LocalStack. 

There are a couple of ways you can install LocalStack. You can install it with a package manager, you can run it on docker with docker-compose, and it is also possible to run LocalStack in a Kubernetes cluster. 

I am going to install LocalStack using docker-compose. You can create different configurations based on your requirements with the docker-compose configuration provided in the LocalStack repository

Prerequisites:

Please make sure to install the following tools on your machine before moving on.

  • docker
  • docker-compose (version 1.9.0+)
  • npm

Docker-compose YAML file template


version: "3.8"
services:
  localstack:
    container_name: "localstack-test"
    image: localstack/localstack:latest
    network_mode: bridge
    privileged: true
    ports:
      - '4566:4566'
    environment:
      - SERVICES=${SERVICES- }
      - DATA_DIR=/tmp/localstack
      - LAMBDA_EXECUTOR=docker-reuse
      - DOCKER_HOST=unix:///var/run/docker.sock
      - AWS_EXECUTION_ENV=true
    volumes:
      - ".volume/tmp/localstack:/tmp/localstack"
      - "/var/run/docker.sock:/var/run/docker.sock"

After creating the `docker-compose.yml` file, get it up and running with the following command.


$ docker-compose up

localstack-test | LocalStack version: 0.13.0
localstack-test | LocalStack build date: 2021-11-23
localstack-test | LocalStack build git hash: b6046487
localstack-test | 
localstack-test | 2021-11-24 07:38:12,906 INFO success: infra entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)
localstack-test | Starting edge router (https port 4566)...
localstack-test | Ready.

 

As there are no errors, LocalStack services are ready for usage.

Serverless Framework is a good option to integrate and use with LocalStack. Let’s install it with npm.


$ npm install -g serverless
$ npm install --save-dev serverless-localstack

Setting Up The App

I am going to create a simple backend that creates, deletes, lists, updates, and retrieves customers that can be used through a REST HTTP API using API Gateway, Lambda, and DynamoDB services.


The figure below provides an overview of the structure of the repository.



The code example below provides an overview of the `getCustomer.py` file. You can get the code at this GitHub Repository.


import os
import json
import boto3

if 'LOCALSTACK_HOSTNAME' in os.environ:
   dynamodb_endpoint = 'http://%s:4566'% os.environ['LOCALSTACK_HOSTNAME']
   dynamodb = boto3.resource('dynamodb',endpoint_url=dynamodb_endpoint)
else:
   dynamodb = boto3.resource('dynamodb')


def getCustomer(event, context):
   table = dynamodb.Table(os.environ['DYNAMODB_TABLE'])

   # fetch Customer from the database
   result = table.get_item(
       Key={
           'id': event['pathParameters']['id']
       }
   )

   # create a response
   response = {
       "statusCode": 200,
       "body": json.dumps(result['Item'])
   }

   return response

The code example below provides an overview of the `serverless.yml` file.

 


service: serverless-rest-api-with-dynamodb

frameworkVersion: ">=1.1.0 <=2.70.0"

provider:
 name: aws
 runtime: python3.8
 environment:
   DYNAMODB_TABLE: ${self:service}-${opt:stage, self:provider.stage}
 ...
functions:
 create:
   handler: customers/createCustomer.createCustomer
   events:
     - http:
         path: customers
         method: post
         cors: true
 ...
resources:
 Resources:
   CustomersDynamoDbTable:
     Type: 'AWS::DynamoDB::Table'
     DeletionPolicy: Retain
 ...

After these steps are complete, the following command will deploy my application to LocalStack.


$ serverless deploy --stage local

The result should be similar to:


I will use the given endpoint to create a customer with the following command.


$ curl -X POST http://localhost:4566/restapis/cfev9cngmk/local/_user_request_/customers --data '{"firstName":"Cem","lastName":"ALTUNER"}'
  

The expected output:

{"id": "4b19151b-51ad-11ec-8e88-fbb757305d9e", "firstName": "Cem", "lastName": "ALTUNER", "createdAt": "1638256527.26767", "updatedAt": "1638256527.26767"}

Serverless Framework is a good option to create and test serverless applications on your local computer with LocalStack. But if you want to test your whole infrastructure, the Infrastructure as a Code approach like Terraform would be a better option. 

Conclusion

LocalStack makes it easier to test, save money, and get things done faster when developing your infrastructure. If you want to test your infrastructure on your local computer, LocalStack can be the right solution for you.