How can I deploy nginx to AWS fargate in code? How can I deploy nginx to AWS fargate in code? docker docker

How can I deploy nginx to AWS fargate in code?


You could use AWS cdk tool to write your infrastructure as code. It's basically a meta framework to create cloudformation templates. Here would be a minimal example to deploy nginx to a loadbalanced ecs fargate service with autoscaling, but you could just remove the last to expressions. The code gets more complicated quickly, when you need more control about what to start

import cdk = require('@aws-cdk/cdk');import ec2 = require('@aws-cdk/aws-ec2');import ecs = require('@aws-cdk/aws-ecs');import ecr = require('@aws-cdk/aws-ecr');export class NginxStack extends cdk.Stack {    constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {        super(scope, id, props);        const vpc = new ec2.VpcNetwork(this, 'MyApiVpc', {            maxAZs: 1        });        const cluster = new ecs.Cluster(this, 'MyApiEcsCluster', {            vpc: vpc        });        const lbfs = new ecs.LoadBalancedFargateService(this, 'MyApiLoadBalancedFargateService', {            cluster: cluster,            cpu: '256',            desiredCount: 1,            // The tag for the docker image is set dynamically by our CI / CD pipeline            image: ecs.ContainerImage.fromDockerHub("nginx"),            memoryMiB: '512',            publicLoadBalancer: true,            containerPort: 80        });        const scaling = lbfs.service.autoScaleTaskCount({            maxCapacity: 5,            minCapacity: 1        });        scaling.scaleOnCpuUtilization('MyApiCpuScaling', {            targetUtilizationPercent: 10        });    }}

I added the link to a specific cdk version, because the most recent build for the docs is a little bit broken.


ECS uses "Task Definitions" instead of docker-compose. In Task Definitions, you define which image and ports to use. We can use docker-compose as well, if we use AWS CLI. But I haven't tried it yet.

So you can create an ECS Fargate based cluster first and then create a Task or Service using the task definition. This will bring up the containers in Fargate.