Using cdk8s to manage your k8s app on Google Cloud — Part 2

Campion
2 min readMar 27, 2020

--

A fair bit of background on k8s is required for this tutorial.

This is a follow up to Part 1, you should read that if you haven’t already.

In Part 2 of this tutorial here, you’ll really get to see the power of cdk8s and the improvements it can have on your deployment workflow.

In the last tutorial, we deployed your microservice by defining a new Service and a new Deployment . Now what if you have a whole lot of microservices?

Let’s refactor our code a bit. Take the Service and Deployment that you defined and we’ll put them into a higher level construct, like this:

export interface MicroServiceProps {
containerName: string
image: string
replicas?: number
}
export class MicroService extends Construct {
constructor(scope: Chart, id: string, props: MicroServiceProps) {
super(scope, id);
const label = { app: Node.of(this).uniqueId }; new Service(this, `service`, {
spec: {
type: 'LoadBalancer',
ports: [ { port: 80, targetPort: 8080 } ],
selector: label
}
});
new Deployment(this, `deployment`, {
spec: {
replicas: props.replicas || 2,
selector: {
matchLabels: label
},
template: {
metadata: { labels: label },
spec: {
containers: [{
name: this.props.containerName,
image: props.image,
ports: [ { containerPort: 8080 } ]
}]
}
}
}
});
}
}

Now if you’re familiar with AWS CDK you’ll recognize how this works. I’m creating a Construct that will create a new Service and new Deployment just like before. We’re also passing in MicroServiceProps so we can change things like the label , image , and number of replicas .

I’ve now abstracted away all the port configuration for the LoadBalancer and deployment containers because in our use case we always want 80 →8080.

Back in our main Chart , we can replace what we had with this:

new MicroService(this, 'microservice1', {
containerName: 'mycontainer1'
image: '<GCR or DockerHub image>',
});

And we can add another microservice just as easily, this time overwriting the default 2 replicas to be 10:

new MicroService(this, 'microservice2', {
containerName: 'mycontainer2'
image: '<GCR or DockerHub image>',
replicas: 10
});

and so on and so forth. As a developer, you’re now spared the pain from repetitively writing the deployment template spec, the port configuration, etc.

You’re now more able to focus on what really matters for your application: the image it runs, and how many replicas it has.

Congrats! You’ve just made your first cdk8s construct!

Be sure to follow along with https://github.com/awslabs/cdk8s as more Constructs are made to simplify your k8s deployments.

--

--