Build and publish container images to any cloud with Infrastructure as Code
Going from a containerized application to a service running in the cloud requires a few steps beyond an application's normal build-and-test cycle. Namely, it means building and publishing a container image in a registry and then consuming that image from your target environment, whether that's Kubernetes, Amazon ECS, or another container orchestrator. It's not enough to just write a Dockerfile — you will need to pick a container registry, decide whether that registry should be public or private, authenticate against it, and ideally automate deploying subsequent updates. Infrastructure as code to the rescue! In this article, we'll see how to build, publish, and consume a simple container image across any cloud, using just a few lines of code.
Approach
The general approach will be to create a new infrastructure as code project that
- Prepares a container registry, either public or private
- Builds and publishes your container image to that registry
- Optionally, consumes the resulting image URL from a containerized task definition in Kubernetes, Amazon ECS, or any other container orchestrator
All told, this will be just a few dozen lines of code. This article demonstrates doing this in AWS, Azure, GCP, DigitalOcean, and Docker Hub, and offers code examples in each supported Pulumi language, namely Python, JavaScript, TypeScript, Go, and C#. These steps will work for any application that has a Dockerfile and is buildable by Docker. In principle, similar steps could be applied if you prefer to build your container image using different means, such as Buildpack.
For purposes of illustration, we'll create a simple Nginx web server whose Dockerfile contains:
FROM nginx
RUN echo "<h1>Hello, World!</h1>" > \
/usr/share/nginx/html/index.htmlNow, let's dive in!
Prepare a Container Registry
The first step is to prepare a new container registry. A registry holds one or more repositories, each of which can store and serve many different container images with different tags and versions. Afterward we'll show how to build and publish to this registry.
The specific details of how to prepare your registry differ by cloud provider, often significantly, particularly when it comes to authenticating. Pick your cloud provider to see the details:
Amazon Elastic Container Registry (ECR)
Amazon Elastic Container Registry (ECR) provides managed Docker container hosting that makes it easy to run containerized applications in your AWS account using Amazon Elastic Container Service (ECS) and Elastic Kubernetes Service (EKS). Each account has a default registry per region, and each registry may have any number of repositories, each for a different Docker image. Each repository can store many versions of that particular image.
Create a New Project
To start, create a new project and ensure it is configured to use your AWS account, and then scaffold your project with the imports and overall program structure that we will fill in one piece at a time:
import * as aws from "@pulumi/aws";
import * as docker from "@pulumi/docker";
// [Placeholder 1: Create a private ECR registry.]
// [Placeholder 2: Get registry info (creds and endpoint).]
// [Placeholder 3: Build and publish the container image.]Provision an ECR Repository
Next, declare a new ECR repository resource:
// Create a private ECR repository.
const repo = new aws.ecr.Repository("my-repo");Authenticate with Temporary ECR Access Token
Next, we will need to generate authentication information to access the repository to build and publish our image. ECR supports this in multiple different ways; however, here, we will demonstrate generating a temporary access token:
// Get registry info (creds and endpoint).
const imageName = repo.repositoryUrl;
const registryInfo = repo.registryId.apply(async id => {
const credentials = await aws.ecr.getCredentials({ registryId: id });
const decodedCredentials = Buffer.from(credentials.authorizationToken, "base64").toString();
const [username, password] = decodedCredentials.split(":");
if (!password || !username) {
throw new Error("Invalid credentials");
}
return {
server: credentials.proxyEndpoint,
username: username,
password: password,
};
});Alternatively, Authenticate with ECR Credential Helper
An alternative approach ECR supports is to use the Docker credential helper from Amazon, which integrates with local IAM settings, adds smart caching, and removes the need for Docker to login. If you elect to go this route, leave out the username/password parts of the docker.ImageRegistry:
// Get registry info (creds and endpoint).
const imageName = repo.repositoryUrl;
const registryInfo = undefined; // use ECR credentials helper.Learn More About ECR
ECR offers many additional options not shown here. This includes configuring advanced IAM permissions, enabling image vulnerability scanning, managing the lifetime of images so that older, unused images are deleted based on configured policies, encrypting images, and more. For details on these advanced capabilities and more, refer to Pulumi's ECR user guide, Pulumi's ECR API reference, or Amazon's product documentation.
To view another cloud provider's registry details, select a new cloud in the switcher above.
At this stage, we can run pulumi up to check that the program works and to provision any necessary cloud resources.
Build and Publish Your Container
Now we are ready to build and publish your container image to the chosen registry. The Docker provider's Image component internally uses the Docker engine to perform the necessary steps to carry this out, including building, tagging, capturing, and streaming container build logs as progress is made and pushing the final result.
Simply pass the path to your application's Dockerfile as the build context, the registry's URL as the image's name, and the registry configuration object built up earlier to facilitate authentication:
// [Existing imports ...]
import * as docker from "@pulumi/docker";
// [Registry configuration as shown above ...]
// Build and publish the container image.
const image = new docker.Image("my-image", {
build: "app",
imageName,
registry,
});
// Export the base and specific version image name.
export const baseImageName = image.baseImageName;
export const fullImageName = image.imageName;Now let's run pulumi up. If you haven't already done so, this will provision the cloud resources, as well as build/publish the container image. As the build runs, you will see Docker build output streamed to your terminal:
$ pulumi up
Updating (dev)
Type Name Status
+ pulumi:pulumi:Stack project-dev created
... cloud-specific resources omitted ...
+ └─ docker:image:Image my-image created
Outputs:
baseImageName: "...cloud-specific url.../my-repo-dc811b0"
fullImageName: "...cloud-specific url.../my-repo-dc811b0:78d0fce7c2450c15a6153b6b11208fcb6b9edea7bb7ef3b7b6194f3fc101a170"Also note the base and versioned image URLs are exported as stack outputs. These are optional but have three benefits:
- As we see here, the CLI will print them after each deployment.
- The CLI can fetch them on-demand, e.g., 'pulumi stack output fullImageName', making it easy to script access to these container images.
- The Pulumi
StackReferencecomponent can be used to depend on this stack from another, allowing us to build higher levels of infrastructure that consume these images.
As an example of (2) in action, let's run the image locally using the exported image name:
$ pulumi stack output fullImageName
...cloud-specific url.../my-repo-dc811b0:78d0fce7c2450c15a6153b6b11208fcb6b9edea7bb7ef3b7b6194f3fc101a170Note that this requires that our client can pull from our provisioned registry, which may require cloud-specific authentication first.
To redeploy changes to the Dockerfile or anything that image depends on, including application code, rerun pulumi up. It will detect the differences, rebuild and re-push the minimal layer changes necessary to update and retag the repository image, and then export the resulting image name.
To see this in action, change the Dockerfile's contents to:
FROM nginx
RUN echo "<h1>Hello, World -- from Pulumi!</h1>" > \
/usr/share/nginx/html/index.htmlAnd then rerun Pulumi -- notice how it detects the change, updates the image, and the versioned image hash changes (indicated by the tilde ~):
$ pulumi up
Updating (dev)
Type Name Status
+ pulumi:pulumi:Stack project-dev created
~ └─ docker:image:Image my-image updated
Outputs:
baseImageName: "...cloud-specific url.../my-repo-dc811b0"
~ fullImageName: "...cloud-specific url.../my-repo-dc811b0:78d0fce7c2450c15a6153b6b11208fcb6b9edea7bb7ef3b7b6194f3fc101a170"The Pulumi Docker Image component supports a number of additional options to control its behavior, including passing build arguments, environment variables, extra options for the Docker build, as well as various controls for image caching. For full details on each of these, refer to the API documentation.
Consume the Container Image
The same container image URLs exported above can be used as inputs to other resources, including infrastructure that will run your container inside of a container orchestration system such as Kubernetes, Amazon ECS, and so on.
This article assumes you already have a containerized environment to deploy to, like a Kubernetes cluster, and have configured your project accordingly. If not, you can provision one using Pulumi first. Pulumi supports many clouds and infrastructure resources, but here are a few starting points to get up and running with:
- AWS Elastic Container Service ECS,
- AWS Elastic Kubernetes Service (EKS),
- Azure Kubernetes Service (AKS),
- Google Cloud Kubernetes Engine (GKE),
- DigitalOcean Kubernetes.
This example demonstrates deploying our Nginx web server as a load balanced service within Kubernetes. To do so, we'll declare our Kubernetes configuration, right inside of our existing program defined above, and export its resulting IP address:
// [Previous imports...]
import * as k8s from "@pulumi/kubernetes";
// [Registry, build, etc, code from above...]
// Create a load balanced Kubernetes service using this image, and export its IP.
const appLabels = { app: "myapp" };
const appDep = new k8s.apps.v1.Deployment("app-dep", {
spec: {
selector: { matchLabels: appLabels },
replicas: 3,
template: {
metadata: { labels: appLabels },
spec: {
containers: [{
name: "myapp",
image: image.imageName,
}],
},
},
},
});
const appSvc = new k8s.core.v1.Service("app-svc", {
metadata: { labels: appLabels },
spec: {
type: "LoadBalancer",
ports: [{ port: 80, targetPort: 80, protocol: "TCP" }],
selector: appLabels,
},
});
export const appIp = appSvc.status.loadBalancer.ingress[0].ip;Notice here that we are referring to the resulting image name from our service specification. All we need to do run a 'pulumi up' and Pulumi will now build, publish, and consume our application's container image from within our Kubernetes cluster:
$ pulumi up
Updating (dev)
Type Name Status
+ pulumi:pulumi:Stack project-dev created
... prior output omitted ...
+ ├─ kubernetes:apps/v1:Deployment app-dep created
+ └─ kubernetes:core/v1:Service app-svc created
Outputs:
appIp : "34.82.32.166"
baseImageName: "...cloud-specific url.../my-repo-dc811b0"
fullImageName: "...cloud-specific url.../my-repo-dc811b0:fcbbd958636e4f8ac02568db7dbf8b89a043e210e917432cf12649aaedfa266c"If this is the first time you've run pulumi up, all of the prior resources will be provisioned first, and in any case, the Kubernetes resources will follow.
Now that our deployment has completed, we can curl the endpoint:
$ curl $(pulumi stack output appIp)
<h1>Hello, World -- from Pulumi!</h1>This image name is the versioned one, meaning that any time a new version is created, Pulumi will detect that it needs to update the Kubernetes deployment which references it, triggering a rollout of the new deployed image. As such, we just need to run pulumi up anytime the application or its Dockerfile changes and Pulumi will detect and trigger a deployment to Kubernetes.
To see this in action, let's change our Dockerfile's contents once more:
FROM nginx
RUN echo "<h1>Hello, World -- from Pulumi and Kubernetes!</h1>" > \
/usr/share/nginx/html/index.htmlAnd then rerun Pulumi -- notice that both the image and the Kubernetes deployment has changed this time:
$ pulumi up
Updating (dev)
Type Name Status Info
+ pulumi:pulumi:Stack project-dev created
~ ├─ docker:image:Image my-image updated
~ └─ kubernetes:core/v1:Deployment app-dep updated [diff: ~spec]
Outputs:
appIp : "34.82.32.166"
baseImageName: "...cloud-specific url.../my-repo-dc811b0"
fullImageName: "...cloud-specific url.../my-repo-dc811b0:36919b56f6b2dedfa879815443c9964d17a89506caed25025328b1d0204a083f"Finally, if we re-curl the endpoint, we will now see that the updated container is now live!
$ curl $(pulumi stack output appIp)
<h1>Hello, World -- from Pulumi and Kubernetes!</h1>And there we go: we have gone from a Dockerfile to a published container image in a container registry of our choosing, which has been used to spin up a load balanced Kubernetes service, and which is now ready for fully automated continuous deployments.
Wrapping Up
In this article, we've seen how easy it is to build, publish, and use container images in many popular public and private container registry options. We have seen how to provision new registries using infrastructure as code and how easy it is to trigger deployments of application updates by running a single pulumi up command.
All of these steps were manually run from a CLI; however, a natural next step is to wire the entire process up to a CI/CD system such as GitHub Actions, GitLab Pipelines, Jenkins, Spinnaker, or [one of the many available options](/docs/guides/continuous-delivery/, so that you can deploy continuously as you merge code. For even more advanced scenarios, we might want to build a custom program such as a CLI that uses the Automation API to perform these actions behind a simpler, purpose-built interface.
Although we've shown a very simple set of infrastructure resources, it would be natural to extend these examples by provisioning other ancillary services that your application needs, including databases, pub/sub topics, queues, metrics and dashboards, and more. Using an infrastructure as code approach to building, publishing, and consuming your container images means you can incrementally add on such infrastructure to the base code shown above and reference them from your containers easily with automatic dependency tracking.
The complete examples in this article are available on GitHub here. Pulumi is open source and free to get started with — give it a try, and get up and running with infrastructure as code for your containers today!