docker logo
Docker v4.2.3, May 24 23

docker.Image

Explore with Pulumi AI

Image builds a Docker image and pushes it Docker and OCI compatible registries. This resource enables running Docker builds as part of a Pulumi deployment.

Note: This resource does not delete tags, locally or remotely, when destroyed.

Cross-platform builds

The Image resource supports cross-platform builds when the Docker engine has cross-platform support enabled via emulators. The Image resource currently supports providing only a single operating system and architecture in the platform field, e.g.: linux/amd64. To enable this support, you may need to install the emulators in the environment running your Pulumi program.

If you are using Linux, you may be using Docker Engine or Docker Desktop for Linux, depending on how you have installed Docker. The FAQ for Docker Desktop for Linux describes the differences and how to select which Docker context is in use.

  • For local development using Docker Desktop, this is enabled by default.

  • For systems using Docker Engine, install the QEMU binaries and register them with using the docker image from github.com/tonistiigi/binfmt:

    docker run --privileged --rm tonistiigi/binfmt --install all
    
  • In a GitHub Actions workflow, the docker/setup-qemu-action can be used instead by adding this step to your workflow file. Example workflow usage:

    name: Pulumi
    on:
      push:
        branches:
          - master
    jobs:
      up:
        name: Preview
        runs-on: ubuntu-latest
        steps:
            # This is the step added:
          - name: Set up QEMU
            uses: docker/setup-qemu-action@v2
            # The ordinary pulumi/actions workflow:
          - uses: actions/checkout@v3
          - uses: pulumi/actions@v4
            with:
              command: preview
              stack-name: org-name/stack-name
            env:
              PULUMI_ACCESS_TOKEN: ${{ secrets.PULUMI_ACCESS_TOKEN }}
    

Example Usage

A Docker image build

using System.Collections.Generic;
using System.Linq;
using Pulumi;
using Docker = Pulumi.Docker;

return await Deployment.RunAsync(() => 
{
    var demoImage = new Docker.Image("demo-image", new()
    {
        Build = new Docker.Inputs.DockerBuildArgs
        {
            Context = ".",
            Dockerfile = "Dockerfile",
        },
        ImageName = "username/image:tag1",
        SkipPush = true,
    });

    return new Dictionary<string, object?>
    {
        ["imageName"] = demoImage.ImageName,
    };
});
package main

import (
	"github.com/pulumi/pulumi-docker/sdk/v4/go/docker"
	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)

func main() {
	pulumi.Run(func(ctx *pulumi.Context) error {
		demoImage, err := docker.NewImage(ctx, "demo-image", &docker.ImageArgs{
			Build: &docker.DockerBuildArgs{
				Context:    pulumi.String("."),
				Dockerfile: pulumi.String("Dockerfile"),
			},
			ImageName: pulumi.String("username/image:tag1"),
			SkipPush:  pulumi.Bool(true),
		})
		if err != nil {
			return err
		}
		ctx.Export("imageName", demoImage.ImageName)
		return nil
	})
}
package generated_program;

import com.pulumi.Context;
import com.pulumi.Pulumi;
import com.pulumi.core.Output;
import com.pulumi.docker.Image;
import com.pulumi.docker.ImageArgs;
import com.pulumi.docker.inputs.DockerBuildArgs;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;

public class App {
    public static void main(String[] args) {
        Pulumi.run(App::stack);
    }

    public static void stack(Context ctx) {
        var demoImage = new Image("demoImage", ImageArgs.builder()        
            .build(DockerBuildArgs.builder()
                .context(".")
                .dockerfile("Dockerfile")
                .build())
            .imageName("username/image:tag1")
            .skipPush(true)
            .build());

        ctx.export("imageName", demoImage.imageName());
    }
}
import pulumi
import pulumi_docker as docker

demo_image = docker.Image("demo-image",
    build=docker.DockerBuildArgs(
        context=".",
        dockerfile="Dockerfile",
    ),
    image_name="username/image:tag1",
    skip_push=True)
pulumi.export("imageName", demo_image.image_name)
import * as pulumi from "@pulumi/pulumi";
import * as docker from "@pulumi/docker";

const demoImage = new docker.Image("demo-image", {
    build: {
        context: ".",
        dockerfile: "Dockerfile",
    },
    imageName: "username/image:tag1",
    skipPush: true,
});
export const imageName = demoImage.imageName;
config: {}
description: A Docker image build
name: image-yaml
outputs:
    imageName: ${demo-image.imageName}
resources:
    demo-image:
        options:
            version: v4.0.0
        properties:
            build:
                context: .
                dockerfile: Dockerfile
            imageName: username/image:tag1
            skipPush: true
        type: docker:Image
runtime: yaml
variables: {}

Docker image build using caching with AWS Elastic Container Registry

using System.Collections.Generic;
using System.Linq;
using Pulumi;
using Aws = Pulumi.Aws;
using Docker = Pulumi.Docker;

return await Deployment.RunAsync(() => 
{
    var ecrRepository = new Aws.Ecr.Repository("ecr-repository", new()
    {
        Name = "docker-repository",
    });

    var authToken = Aws.Ecr.GetAuthorizationToken.Invoke(new()
    {
        RegistryId = ecrRepository.RegistryId,
    });

    var myAppImage = new Docker.Image("my-app-image", new()
    {
        Build = new Docker.Inputs.DockerBuildArgs
        {
            Args = 
            {
                { "BUILDKIT_INLINE_CACHE", "1" },
            },
            CacheFrom = new Docker.Inputs.CacheFromArgs
            {
                Images = new[]
                {
                    ecrRepository.RepositoryUrl.Apply(repositoryUrl => $"{repositoryUrl}:latest"),
                },
            },
            Context = "app/",
            Dockerfile = "Dockerfile",
        },
        ImageName = ecrRepository.RepositoryUrl.Apply(repositoryUrl => $"{repositoryUrl}:latest"),
        Registry = new Docker.Inputs.RegistryArgs
        {
            Password = Output.CreateSecret(authToken.Apply(getAuthorizationTokenResult => getAuthorizationTokenResult.Password)),
            Server = ecrRepository.RepositoryUrl,
        },
    });

    return new Dictionary<string, object?>
    {
        ["imageName"] = myAppImage.ImageName,
    };
});
package main

import (
	"fmt"

	"github.com/pulumi/pulumi-aws/sdk/v5/go/aws/ecr"
	"github.com/pulumi/pulumi-docker/sdk/v4/go/docker"
	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)

func main() {
	pulumi.Run(func(ctx *pulumi.Context) error {
		ecrRepository, err := ecr.NewRepository(ctx, "ecr-repository", &ecr.RepositoryArgs{
			Name: pulumi.String("docker-repository"),
		})
		if err != nil {
			return err
		}
		authToken := ecr.GetAuthorizationTokenOutput(ctx, ecr.GetAuthorizationTokenOutputArgs{
			RegistryId: ecrRepository.RegistryId,
		}, nil)
		myAppImage, err := docker.NewImage(ctx, "my-app-image", &docker.ImageArgs{
			Build: &docker.DockerBuildArgs{
				Args: pulumi.StringMap{
					"BUILDKIT_INLINE_CACHE": pulumi.String("1"),
				},
				CacheFrom: &docker.CacheFromArgs{
					Images: pulumi.StringArray{
						ecrRepository.RepositoryUrl.ApplyT(func(repositoryUrl string) (string, error) {
							return fmt.Sprintf("%v:latest", repositoryUrl), nil
						}).(pulumi.StringOutput),
					},
				},
				Context:    pulumi.String("app/"),
				Dockerfile: pulumi.String("Dockerfile"),
			},
			ImageName: ecrRepository.RepositoryUrl.ApplyT(func(repositoryUrl string) (string, error) {
				return fmt.Sprintf("%v:latest", repositoryUrl), nil
			}).(pulumi.StringOutput),
			Registry: &docker.RegistryArgs{
				Password: pulumi.ToSecret(authToken.ApplyT(func(authToken ecr.GetAuthorizationTokenResult) (string, error) {
					return authToken.Password, nil
				}).(pulumi.StringOutput)).(pulumi.StringOutput),
				Server: ecrRepository.RepositoryUrl,
			},
		})
		if err != nil {
			return err
		}
		ctx.Export("imageName", myAppImage.ImageName)
		return nil
	})
}
package generated_program;

import com.pulumi.Context;
import com.pulumi.Pulumi;
import com.pulumi.core.Output;
import com.pulumi.aws.ecr.Repository;
import com.pulumi.aws.ecr.RepositoryArgs;
import com.pulumi.aws.ecr.EcrFunctions;
import com.pulumi.aws.ecr.inputs.GetAuthorizationTokenArgs;
import com.pulumi.docker.Image;
import com.pulumi.docker.ImageArgs;
import com.pulumi.docker.inputs.DockerBuildArgs;
import com.pulumi.docker.inputs.CacheFromArgs;
import com.pulumi.docker.inputs.RegistryArgs;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;

public class App {
    public static void main(String[] args) {
        Pulumi.run(App::stack);
    }

    public static void stack(Context ctx) {
        var ecrRepository = new Repository("ecrRepository", RepositoryArgs.builder()        
            .name("docker-repository")
            .build());

        final var authToken = EcrFunctions.getAuthorizationToken(GetAuthorizationTokenArgs.builder()
            .registryId(ecrRepository.registryId())
            .build());

        var myAppImage = new Image("myAppImage", ImageArgs.builder()        
            .build(DockerBuildArgs.builder()
                .args(Map.of("BUILDKIT_INLINE_CACHE", "1"))
                .cacheFrom(CacheFromArgs.builder()
                    .images(ecrRepository.repositoryUrl().applyValue(repositoryUrl -> String.format("%s:latest", repositoryUrl)))
                    .build())
                .context("app/")
                .dockerfile("Dockerfile")
                .build())
            .imageName(ecrRepository.repositoryUrl().applyValue(repositoryUrl -> String.format("%s:latest", repositoryUrl)))
            .registry(RegistryArgs.builder()
                .password(Output.ofSecret(authToken.applyValue(getAuthorizationTokenResult -> getAuthorizationTokenResult).applyValue(authToken -> authToken.applyValue(getAuthorizationTokenResult -> getAuthorizationTokenResult.password()))))
                .server(ecrRepository.repositoryUrl())
                .build())
            .build());

        ctx.export("imageName", myAppImage.imageName());
    }
}
import pulumi
import pulumi_aws as aws
import pulumi_docker as docker

ecr_repository = aws.ecr.Repository("ecr-repository", name="docker-repository")
auth_token = aws.ecr.get_authorization_token_output(registry_id=ecr_repository.registry_id)
my_app_image = docker.Image("my-app-image",
    build=docker.DockerBuildArgs(
        args={
            "BUILDKIT_INLINE_CACHE": "1",
        },
        cache_from=docker.CacheFromArgs(
            images=[ecr_repository.repository_url.apply(lambda repository_url: f"{repository_url}:latest")],
        ),
        context="app/",
        dockerfile="Dockerfile",
    ),
    image_name=ecr_repository.repository_url.apply(lambda repository_url: f"{repository_url}:latest"),
    registry=docker.RegistryArgs(
        password=pulumi.Output.secret(auth_token.password),
        server=ecr_repository.repository_url,
    ))
pulumi.export("imageName", my_app_image.image_name)
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
import * as docker from "@pulumi/docker";

const ecrRepository = new aws.ecr.Repository("ecr-repository", {name: "docker-repository"});
const authToken = aws.ecr.getAuthorizationTokenOutput({
    registryId: ecrRepository.registryId,
});
const myAppImage = new docker.Image("my-app-image", {
    build: {
        args: {
            BUILDKIT_INLINE_CACHE: "1",
        },
        cacheFrom: {
            images: [pulumi.interpolate`${ecrRepository.repositoryUrl}:latest`],
        },
        context: "app/",
        dockerfile: "Dockerfile",
    },
    imageName: pulumi.interpolate`${ecrRepository.repositoryUrl}:latest`,
    registry: {
        password: pulumi.secret(authToken.password),
        server: ecrRepository.repositoryUrl,
    },
});
export const imageName = myAppImage.imageName;
config: {}
description: Docker image build using caching with AWS Elastic Container Registry
name: image-caching-yaml
outputs:
    imageName: ${my-app-image.imageName}
resources:
    ecr-repository:
        properties:
            name: docker-repository
        type: aws:ecr:Repository
    my-app-image:
        options:
            version: v4.1.2
        properties:
            build:
                args:
                    BUILDKIT_INLINE_CACHE: "1"
                cacheFrom:
                    images:
                        - ${ecr-repository.repositoryUrl}:latest
                context: app/
                dockerfile: Dockerfile
            imageName: ${ecr-repository.repositoryUrl}:latest
            registry:
                password:
                    fn::secret: ${authToken.password}
                server: ${ecr-repository.repositoryUrl}
        type: docker:Image
runtime: yaml
variables:
    authToken:
        fn::aws:ecr:getAuthorizationToken:
            registryId: ${ecr-repository.registryId}

Create Image Resource

new Image(name: string, args: ImageArgs, opts?: CustomResourceOptions);
@overload
def Image(image_name,
          build,
          local_image_name=None,
          registry=None,
          skip_push=None,
          opts=None)
@overload
def Image(image_name,
          build,
          local_image_name=None,
          registry=None,
          skip_push=None,
          opts=None)
func NewImage(ctx *Context, name string, args ImageArgs, opts ...ResourceOption) (*Image, error)
public Image(string name, ImageArgs args, CustomResourceOptions? opts = null)
public Image(String name, ImageArgs args)
public Image(String name, ImageArgs args, CustomResourceOptions options)
type: docker:Image
properties: # The arguments to resource properties.
options: # Bag of options to control resource's behavior.

name string
The unique name of the resource.
args ImageArgs
The arguments to resource properties.
opts CustomResourceOptions
Bag of options to control resource's behavior.
image_name
build
local_image_name
registry
skip_push
opts
ctx Context
Context object for the current deployment.
name string
The unique name of the resource.
args ImageArgs
The arguments to resource properties.
opts ResourceOption
Bag of options to control resource's behavior.
name string
The unique name of the resource.
args ImageArgs
The arguments to resource properties.
opts CustomResourceOptions
Bag of options to control resource's behavior.
name String
The unique name of the resource.
args ImageArgs
The arguments to resource properties.
options CustomResourceOptions
Bag of options to control resource's behavior.

Image Resource Properties

To learn more about resource properties and how to use them, see Inputs and Outputs in the Architecture and Concepts docs.

Inputs

The Image resource accepts the following input properties:

ImageName string

The image name

Build DockerBuildArgs

The Docker build context

Registry RegistryArgs

The registry to push the image to

SkipPush bool

A flag to skip a registry push.

ImageName string

The image name

Build DockerBuildArgs

The Docker build context

Registry RegistryArgs

The registry to push the image to

SkipPush bool

A flag to skip a registry push.

imageName String

The image name

build DockerBuildArgs

The Docker build context

registry RegistryArgs

The registry to push the image to

skipPush Boolean

A flag to skip a registry push.

imageName string

The image name

build DockerBuildArgs

The Docker build context

registry RegistryArgs

The registry to push the image to

skipPush boolean

A flag to skip a registry push.

image_name str

The image name

build DockerBuildArgs

The Docker build context

registry RegistryArgs

The registry to push the image to

skip_push bool

A flag to skip a registry push.

imageName String

The image name

build Property Map

The Docker build context

registry Property Map

The registry to push the image to

skipPush Boolean

A flag to skip a registry push.

Outputs

All input properties are implicitly available as output properties. Additionally, the Image resource produces the following output properties:

BaseImageName string

The fully qualified image name that was pushed to the registry.

Context string

The path to the build context to use.

Dockerfile string

The location of the Dockerfile relative to the docker build context.

Id string

The provider-assigned unique ID for this managed resource.

RegistryServer string

The name of the registry server hosting the image.

RepoDigest string

The digest of the manifest pushed to the registry, e.g.: repo[:tag]@:

BaseImageName string

The fully qualified image name that was pushed to the registry.

Context string

The path to the build context to use.

Dockerfile string

The location of the Dockerfile relative to the docker build context.

Id string

The provider-assigned unique ID for this managed resource.

RegistryServer string

The name of the registry server hosting the image.

RepoDigest string

The digest of the manifest pushed to the registry, e.g.: repo[:tag]@:

baseImageName String

The fully qualified image name that was pushed to the registry.

context String

The path to the build context to use.

dockerfile String

The location of the Dockerfile relative to the docker build context.

id String

The provider-assigned unique ID for this managed resource.

registryServer String

The name of the registry server hosting the image.

repoDigest String

The digest of the manifest pushed to the registry, e.g.: repo[:tag]@:

baseImageName string

The fully qualified image name that was pushed to the registry.

context string

The path to the build context to use.

dockerfile string

The location of the Dockerfile relative to the docker build context.

id string

The provider-assigned unique ID for this managed resource.

registryServer string

The name of the registry server hosting the image.

repoDigest string

The digest of the manifest pushed to the registry, e.g.: repo[:tag]@:

base_image_name str

The fully qualified image name that was pushed to the registry.

context str

The path to the build context to use.

dockerfile str

The location of the Dockerfile relative to the docker build context.

id str

The provider-assigned unique ID for this managed resource.

registry_server str

The name of the registry server hosting the image.

repo_digest str

The digest of the manifest pushed to the registry, e.g.: repo[:tag]@:

baseImageName String

The fully qualified image name that was pushed to the registry.

context String

The path to the build context to use.

dockerfile String

The location of the Dockerfile relative to the docker build context.

id String

The provider-assigned unique ID for this managed resource.

registryServer String

The name of the registry server hosting the image.

repoDigest String

The digest of the manifest pushed to the registry, e.g.: repo[:tag]@:

Supporting Types

BuilderVersion

BuilderV1
BuilderV1

The first generation builder for Docker Daemon

BuilderBuildKit
BuilderBuildKit

The builder based on moby/buildkit project

BuilderVersionBuilderV1
BuilderV1

The first generation builder for Docker Daemon

BuilderVersionBuilderBuildKit
BuilderBuildKit

The builder based on moby/buildkit project

BuilderV1
BuilderV1

The first generation builder for Docker Daemon

BuilderBuildKit
BuilderBuildKit

The builder based on moby/buildkit project

BuilderV1
BuilderV1

The first generation builder for Docker Daemon

BuilderBuildKit
BuilderBuildKit

The builder based on moby/buildkit project

BUILDER_V1
BuilderV1

The first generation builder for Docker Daemon

BUILDER_BUILD_KIT
BuilderBuildKit

The builder based on moby/buildkit project

"BuilderV1"
BuilderV1

The first generation builder for Docker Daemon

"BuilderBuildKit"
BuilderBuildKit

The builder based on moby/buildkit project

CacheFrom

Images List<string>

Specifies cached images

Images []string

Specifies cached images

images List<String>

Specifies cached images

images string[]

Specifies cached images

images Sequence[str]

Specifies cached images

images List<String>

Specifies cached images

DockerBuild

Args Dictionary<string, string>

An optional map of named build-time argument variables to set during the Docker build. This flag allows you to pass build-time variablesthat can be accessed like environment variables inside the RUN instruction.

BuilderVersion Pulumi.Docker.BuilderVersion

The version of the Docker builder.

CacheFrom CacheFrom

A list of image names to use as build cache. Images provided must have a cache manifest. Must provide authentication to cache registry.

Context string

The path to the build context to use.

Dockerfile string

The path to the Dockerfile to use.

Platform string

The architecture of the platform you want to build this image for, e.g. linux/arm64.

Target string

The target of the Dockerfile to build

Args map[string]string

An optional map of named build-time argument variables to set during the Docker build. This flag allows you to pass build-time variablesthat can be accessed like environment variables inside the RUN instruction.

BuilderVersion BuilderVersion

The version of the Docker builder.

CacheFrom CacheFrom

A list of image names to use as build cache. Images provided must have a cache manifest. Must provide authentication to cache registry.

Context string

The path to the build context to use.

Dockerfile string

The path to the Dockerfile to use.

Platform string

The architecture of the platform you want to build this image for, e.g. linux/arm64.

Target string

The target of the Dockerfile to build

args Map<String,String>

An optional map of named build-time argument variables to set during the Docker build. This flag allows you to pass build-time variablesthat can be accessed like environment variables inside the RUN instruction.

builderVersion BuilderVersion

The version of the Docker builder.

cacheFrom CacheFrom

A list of image names to use as build cache. Images provided must have a cache manifest. Must provide authentication to cache registry.

context String

The path to the build context to use.

dockerfile String

The path to the Dockerfile to use.

platform String

The architecture of the platform you want to build this image for, e.g. linux/arm64.

target String

The target of the Dockerfile to build

args {[key: string]: string}

An optional map of named build-time argument variables to set during the Docker build. This flag allows you to pass build-time variablesthat can be accessed like environment variables inside the RUN instruction.

builderVersion BuilderVersion

The version of the Docker builder.

cacheFrom CacheFrom

A list of image names to use as build cache. Images provided must have a cache manifest. Must provide authentication to cache registry.

context string

The path to the build context to use.

dockerfile string

The path to the Dockerfile to use.

platform string

The architecture of the platform you want to build this image for, e.g. linux/arm64.

target string

The target of the Dockerfile to build

args Mapping[str, str]

An optional map of named build-time argument variables to set during the Docker build. This flag allows you to pass build-time variablesthat can be accessed like environment variables inside the RUN instruction.

builder_version BuilderVersion

The version of the Docker builder.

cache_from CacheFrom

A list of image names to use as build cache. Images provided must have a cache manifest. Must provide authentication to cache registry.

context str

The path to the build context to use.

dockerfile str

The path to the Dockerfile to use.

platform str

The architecture of the platform you want to build this image for, e.g. linux/arm64.

target str

The target of the Dockerfile to build

args Map<String>

An optional map of named build-time argument variables to set during the Docker build. This flag allows you to pass build-time variablesthat can be accessed like environment variables inside the RUN instruction.

builderVersion "BuilderV1" | "BuilderBuildKit"

The version of the Docker builder.

cacheFrom Property Map

A list of image names to use as build cache. Images provided must have a cache manifest. Must provide authentication to cache registry.

context String

The path to the build context to use.

dockerfile String

The path to the Dockerfile to use.

platform String

The architecture of the platform you want to build this image for, e.g. linux/arm64.

target String

The target of the Dockerfile to build

Registry

Password string

The password to authenticate to the registry. Does not cause image rebuild when changed.

Server string

The URL of the Docker registry server

Username string

The username to authenticate to the registry. Does not cause image rebuild when changed.

Password string

The password to authenticate to the registry. Does not cause image rebuild when changed.

Server string

The URL of the Docker registry server

Username string

The username to authenticate to the registry. Does not cause image rebuild when changed.

password String

The password to authenticate to the registry. Does not cause image rebuild when changed.

server String

The URL of the Docker registry server

username String

The username to authenticate to the registry. Does not cause image rebuild when changed.

password string

The password to authenticate to the registry. Does not cause image rebuild when changed.

server string

The URL of the Docker registry server

username string

The username to authenticate to the registry. Does not cause image rebuild when changed.

password str

The password to authenticate to the registry. Does not cause image rebuild when changed.

server str

The URL of the Docker registry server

username str

The username to authenticate to the registry. Does not cause image rebuild when changed.

password String

The password to authenticate to the registry. Does not cause image rebuild when changed.

server String

The URL of the Docker registry server

username String

The username to authenticate to the registry. Does not cause image rebuild when changed.

Package Details

Repository
Docker pulumi/pulumi-docker
License
Apache-2.0
Notes

This Pulumi package is based on the docker Terraform Provider.