AWS Fargate with CDK

In this post, you learn how to use AWS CDK to deploy containers in AWS Fargate. AWS Fargate is a service in AWS which enables us to deploy Docker container applications in a serverless manner. In this demo, we will deploy a very basic webserver which returns hello world using AWS Fargate and CDK. Of course, you can also simply reference a docker image in docker hub instead of building something from scratch.

First thing’s first, let’s initialize an empty CDK typescript project:

cdk init –language=typescript.

Then we go to package.json to declare the dependencies for our project. Add the following modules the dependencies:

npm install @aws-cdk/aws-ecs @aws-cdk/aws-ecs-patterns @aws-cdk/aws-ecr-assets --save

By default, CDK deploys the VPC for you, but if you want control over your VPC, go ahead and import EC2 Module and add the VPC. Then go to the lib folder and the typescript file for your application stack.

Add the following import statements to before class declaration:

import * as cdk from ‘@aws-cdk/core’; import * as ecs from ‘@aws-cdk/aws-ecs’; import * as patterns from ‘@aws-cdk/aws-ecs-patterns’; import * as path from ‘path’; import { DockerImageAsset } from ‘@aws-cdk/aws-ecr-assets’;

I have created a folder ‘containers’ where I place my Dockerfile and the relevant files.x

const dockerAsset= new DockerImageAsset(this, 'dockerasset',{
  directory:path.join(__dirname, '..', 'containers')
});

This line tells CDK that our docker assets are located in the containers folder.

Then I add a load balanced fargate Service, and let the task be the one I declared in Docker (basic webserver):

const fargateLB=new patterns.ApplicationLoadBalancedFargateService(this, 'fargateloadbalancer',{
  taskImageOptions:{
    image:ecs.ContainerImage.fromDockerImageAsset(dockerAsset),
  },
})

Keep in mind, that the connection to this load balancer takes place over http, so you don’t want to use it as an internet facing load balancer. Also, note that there are many option which you can enable while creating the fargate service. You could add certificates, DNS, Logging…

Now we have created the parts regarding CDK and Fargate, but we also need to implement a minimal webserver. To do that, create a folder called ‘container’ in you project directory and add the following files:

Dockerfile,
package.json,
index.html

Index.json:

hello world from lighttpd

package.json:

{
"name": "test-webserver",
"version": "1.0.0",
"description": "",
"main": "",
"scripts": {
    "docker:build": "docker build . -t lighttpd",
    "docker:run": "docker run -d --name lighttpd -p 8080:80 lighttpd"
},
"author": "",
"license": "ISC",
"dependencies": {
},
"devDependencies": {
    "@types/express": "^4.17.8",
    "@types/node": "^14.10.0",
    "typescript": "^4.0.2"
} }

Dockerfile:

FROM alpine

RUN apk update \
    && apk add lighttpd \
    && rm -rf /var/cache/apk/*

COPY ./index.html /var/www/localhost/htdocs

CMD ["lighttpd","-D","-f","/etc/lighttpd/lighttpd.conf"]

Now we are ready to verify our cdk stack. First run ‘npm run build’ which compiles typescript to javascript. Then run cdk synth. This should give a cloud formation template. If it returns an error, go to previous steps and verify your work. Before you can deploy this applicaion, you need to bootsrap your environment. To do that, run the following.

cdk bootstrap aws://youraccountID/yourregion

set CDK_NEW_BOOTSTRAP=1
cdk bootstrap aws://youraccountID/yourregion

Now you are ready to deploy your cdk app.

cdk deploy

Some more useful cdk commands:

cdk ls //lists the stacks in your application
cdk diff //shows the difference of your current deployed stack and your local stack
cdk doctor //*kind of* verifies your cdk stack for warnings

After deploying successfully, CDK gives you a link to the load balancer where you can verify your work. Please don’t forget to run cdk destroy to avoid incuring unwanted costs when you are done.

The source code on github: https://github.com/pedramha/cdk-fargate

This project is maintained by pedramha