

# Docker samples for CodeBuild
<a name="sample-docker-section"></a>

This section describes sample integrations between Docker and AWS CodeBuild.


| Sample | Description | 
| --- | --- | 
|  [Docker in custom image sample for CodeBuild](sample-docker-custom-image.md)  |  This sample builds and runs a Docker image by using CodeBuild and a custom Docker build image (`docker:dind` in Docker Hub).   | 
|  [Docker image build server sample for CodeBuild](sample-docker-server.md)  |  This sample offloads your Docker builds to a managed image build server.   | 
|  [Windows Docker builds sample for CodeBuild](sample-windows-docker-custom-image.md)  |  This sample builds and runs a Windows Docker image by using CodeBuild.  | 
|  ['Publish Docker image to an Amazon ECR image repository' sample for CodeBuild](sample-docker.md)  |  This sample produces as build output a Docker image and then pushes the Docker image to an Amazon Elastic Container Registry (Amazon ECR) image repository.   | 
|  [Private registry with AWS Secrets Manager sample for CodeBuild](sample-private-registry.md)  |  This sample shows you how to use a Docker image that is stored in a private registry as your CodeBuild runtime environment.  | 

# Docker in custom image sample for CodeBuild
<a name="sample-docker-custom-image"></a>

The following sample builds and runs a Docker image by using AWS CodeBuild and a custom Docker build image (`docker:dind` in Docker Hub). 

To learn how to build a Docker image by using a build image provided by CodeBuild with Docker support instead, see our ['Publish Docker image to Amazon ECR' sample](sample-docker.md).

**Important**  
Running this sample might result in charges to your AWS account. These include possible charges for CodeBuild and for AWS resources and actions related to Amazon S3, AWS KMS, and CloudWatch Logs. For more information, see [CodeBuild pricing](http://aws.amazon.com/codebuild/pricing), [Amazon S3 pricing](http://aws.amazon.com/s3/pricing), [AWS Key Management Service pricing](http://aws.amazon.com/kms/pricing), and [Amazon CloudWatch pricing](http://aws.amazon.com/cloudwatch/pricing).

**Topics**
+ [Run the Docker in custom image sample](#sample-docker-custom-image-running)

## Run the Docker in custom image sample
<a name="sample-docker-custom-image-running"></a>

Use the following procedure to run the Docker in custom image sample. For more information about this sample, see [Docker in custom image sample for CodeBuild](#sample-docker-custom-image).

**To run the Docker in custom image sample**

1. Create the files as described in the [Directory structure](#sample-docker-custom-image-dir) and [Files](#sample-docker-custom-image-files) sections of this topic, and then upload them to an S3 input bucket or an AWS CodeCommit, GitHub, or Bitbucket repository. 
**Important**  
Do not upload `(root directory name)`, just the files inside of `(root directory name)`.   
If you are using an S3 input bucket, be sure to create a ZIP file that contains the files, and then upload it to the input bucket. Do not add `(root directory name)` to the ZIP file, just the files inside of `(root directory name)`.

1. Create a build project, run the build, and view related build information.

   If you use the AWS CLI to create the build project, the JSON-formatted input to the `create-project` command might look similar to this. (Replace the placeholders with your own values.)

   ```
   {
     "name": "sample-docker-custom-image-project",
     "source": {
       "type": "S3",
       "location": "codebuild-region-ID-account-ID-input-bucket/DockerCustomImageSample.zip"
     },
     "artifacts": {
       "type": "NO_ARTIFACTS"
     },
     "environment": {
       "type": "LINUX_CONTAINER",
       "image": "docker:dind",
       "computeType": "BUILD_GENERAL1_SMALL",
       "privilegedMode": false
     },
     "serviceRole": "arn:aws:iam::account-ID:role/role-name",
     "encryptionKey": "arn:aws:kms:region-ID:account-ID:key/key-ID"
   }
   ```
**Note**  
By default, Docker daemon is enabled for non-VPC builds. If you would like to use Docker containers for VPC builds, see [Runtime Privilege and Linux Capabilities](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) on the Docker Docs website and enable privileged mode. Also, Windows does not support privileged mode.

1. To see the build results, look in the build's log for the string `Hello, World!`. For more information, see [View build details](view-build-details.md).

### Directory structure
<a name="sample-docker-custom-image-dir"></a>

This sample assumes this directory structure.

```
(root directory name)
├── buildspec.yml
└── Dockerfile
```

### Files
<a name="sample-docker-custom-image-files"></a>

The base image of the operating system used in this sample is Ubuntu. The sample uses these files.

`buildspec.yml` (in `(root directory name)`)

```
version: 0.2

phases:
  pre_build:
    commands:
      - docker build -t helloworld .
  build:
    commands:
      - docker images
      - docker run helloworld echo "Hello, World!"
```

`Dockerfile` (in `(root directory name)`)

```
FROM maven:3.3.9-jdk-8
 
RUN echo "Hello World"
```

# Docker image build server sample for CodeBuild
<a name="sample-docker-server"></a>

The following sample offloads your Docker builds to a managed image build server. You can adapt this sample to provision a dedicated and managed Docker image build server in your CodeBuild project configuration. Note that the provisioned instance is active while builds are actively run for the project, and the instance is stopped when builds are not running. The provisioned instance is stored for up to a month before it is recycled. For more information, see [ CodeBuild Docker Server Capability](https://aws.amazon.com/blogs//aws/accelerate-ci-cd-pipelines-with-the-new-aws-codebuild-docker-server-capability).

**Important**  
Running this sample might result in charges to your AWS account. These include possible charges for CodeBuild and for AWS resources and actions related to Amazon S3, AWS KMS, and CloudWatch Logs. For more information, see [CodeBuild pricing](http://aws.amazon.com/codebuild/pricing), [Amazon S3 pricing](http://aws.amazon.com/s3/pricing), [AWS Key Management Service pricing](http://aws.amazon.com/kms/pricing), and [Amazon CloudWatch pricing](http://aws.amazon.com/cloudwatch/pricing).

**Topics**
+ [Configure a Docker server](#sample-docker-server-running)

## Configure a Docker server
<a name="sample-docker-server-running"></a>

Use the following procedure to provision a dedicated compute environment for a CodeBuild project that manages Docker workloads and stores Docker image layers. 

**To configure a Docker server**

1. Create the files as described in the [Directory structure](#sample-docker-server-dir) and [Files](#sample-docker-server-files) sections of this topic, and then upload them to an S3 input bucket or an AWS CodeCommit, GitHub, or Bitbucket repository. 
**Important**  
Do not upload `(root directory name)`, just the files inside of `(root directory name)`.   
If you are using an S3 input bucket, be sure to create a ZIP file that contains the files, and then upload it to the input bucket. Do not add `(root directory name)` to the ZIP file, just the files inside of `(root directory name)`.

1. Create a build project, run the build, and view related build information:

   1. In the **Environment** section of the console, choose **Additional configuration**, navigate to **Docker server configuration**, and then select **Enable docker server for this project**. You can then choose the **Docker server compute type** and supply a **Registry credential**.

   1. If you use the AWS CLI to create the build project, the JSON-formatted input to the `create-project` command might look similar to this. (Replace the placeholders with your own values.)

      ```
      {
        "name": "sample-docker-custom-image-project",
        "source": {
          "type": "S3",
          "location": "codebuild-region-ID-account-ID-input-bucket/DockerServerSample.zip"
        },
        "artifacts": {
          "type": "NO_ARTIFACTS"
        },
        "environment": {
          "type": "LINUX_CONTAINER",
          "image": "aws/codebuild/amazonlinux-x86_64-standard:5.0",
          "computeType": "BUILD_GENERAL1_LARGE",
          "dockerServer": [ 
               { 
                  "computeType": "BUILD_GENERAL1_LARGE",
                  "securityGroupIds": [ "security-groups-ID" ]
               }
            ]
        },
        "serviceRole": "arn:aws:iam::account-ID:role/role-name"
      }
      ```
**Note**  
Security groups configured for Docker servers should allow ingress network traffic from the VPC configured in the project. They should allow ingress on port 9876.

1. To see the build results, look in the build's log for the string `Hello, World!`. For more information, see [View build details](view-build-details.md).

### Directory structure
<a name="sample-docker-server-dir"></a>

This sample assumes this directory structure.

```
(root directory name)
├── buildspec.yml
└── Dockerfile
```

### Files
<a name="sample-docker-server-files"></a>

The base image of the operating system used in this sample is Ubuntu. The sample uses these files.

`buildspec.yml` (in `(root directory name)`)

```
version: 0.2

phases:
  build:
    commands:
      - docker buildx build -t helloworld --load .
      - docker run helloworld echo "Hello, World!"
```

`Dockerfile` (in `(root directory name)`)

```
FROM public.ecr.aws/amazonlinux/amazonlinux:latest 
 
RUN echo "Hello World"
```

# Windows Docker builds sample for CodeBuild
<a name="sample-windows-docker-custom-image"></a>

The following sample builds and runs a Windows Docker image by using CodeBuild.

**Topics**
+ [Run Windows Docker builds sample](#sample-windows-docker-build-running)

## Run Windows Docker builds sample
<a name="sample-windows-docker-build-running"></a>

Use the following procedure to run the Windows Docker builds.

**To run Windows Docker builds sample**

1. Create the files as described in the [Directory structure](#sample-windows-docker-custom-image-dir) and [Files](#sample-windows-docker-custom-image-files) sections of this topic, and then upload them to an S3 input bucket or an AWS CodeCommit, GitHub, or Bitbucket repository. 
**Important**  
Do not upload `(root directory name)`, just the files inside of `(root directory name)`.   
If you are using an S3 input bucket, be sure to create a ZIP file that contains the files, and then upload it to the input bucket. Do not add `(root directory name)` to the ZIP file, just the files inside of `(root directory name)`.

1. Create a `WINDOWS_EC2` fleet.

   If you use the AWS CLI to create the fleet, the JSON-formatted input to the `create-fleet` command might look similar to this. (Replace the placeholders with your own values.)

   ```
   {
     "name": "fleet-name",
     "baseCapacity": 1,
     "environmentType": "WINDOWS_EC2",
     "computeType": "BUILD_GENERAL1_MEDIUM"
   }
   ```

1. Create a build project, run the build, and view related build information.

   If you use the AWS CLI to create the build project, the JSON-formatted input to the `create-project` command might look similar to this. (Replace the placeholders with your own values.)

   ```
   {
     "name": "project-name",
     "source": {
       "type": "S3",
       "location": "bucket-name/DockerImageSample.zip"
     },
     "artifacts": {
       "type": "NO_ARTIFACTS"
     },
     "environment": {
       "type": "WINDOWS_EC2",
       "image": "Windows",
       "computeType": "BUILD_GENERAL1_MEDIUM",
       "fleet": {
          "fleetArn": "fleet-arn"
       }
     },
     "serviceRole": "arn:aws:iam::account-ID:role/role-name"
   }
   ```

1. To see the build results, look in the build's log for the string `Hello, World!`. For more information, see [View build details](view-build-details.md).

### Directory structure
<a name="sample-windows-docker-custom-image-dir"></a>

This sample assumes this directory structure.

```
(root directory name)
├── buildspec.yml
└── Dockerfile
```

### Files
<a name="sample-windows-docker-custom-image-files"></a>

The base image of the operating system used in this sample is `mcr.microsoft.com/windows/servercore:ltsc2022`. The sample uses these files.

`buildspec.yml` (in `(root directory name)`)

```
version: 0.2

phases:
  pre_build:
    commands:
      - docker build -t helloworld .
  build:
    commands:
      - docker images
      - docker run helloworld powershell -Command "Write-Host 'Hello World!'"
```

`Dockerfile` (in `(root directory name)`)

```
FROM mcr.microsoft.com/windows/servercore:ltsc2022

RUN powershell -Command "Write-Host 'Hello World'"
```

# 'Publish Docker image to an Amazon ECR image repository' sample for CodeBuild
<a name="sample-docker"></a>

This sample produces as build output a Docker image and then pushes the Docker image to an Amazon Elastic Container Registry (Amazon ECR) image repository. You can adapt this sample to push the Docker image to Docker Hub. For more information, see [Adapt the 'Publish Docker image to Amazon ECR' sample to push to Docker Hub](sample-docker-docker-hub.md).

To learn how to build a Docker image by using a custom Docker build image (`docker:dind` in Docker Hub), see our [Docker in custom image sample](sample-docker-custom-image.md).

This sample was tested referencing `golang:1.12`.

This sample uses the new multi-stage Docker builds feature, which produces a Docker image as build output. It then pushes the Docker image to an Amazon ECR image repository. Multi-stage Docker image builds help to reduce the size of the final Docker image. For more information, see [Use multi-stage builds with Docker](https://docs.docker.com/engine/userguide/eng-image/multistage-build/).

**Important**  
Running this sample might result in charges to your AWS account. These include possible charges for AWS CodeBuild and for AWS resources and actions related to Amazon S3, AWS KMS, CloudWatch Logs, and Amazon ECR. For more information, see [CodeBuild pricing](http://aws.amazon.com/codebuild/pricing), [Amazon S3 pricing](http://aws.amazon.com/s3/pricing), [AWS Key Management Service pricing](http://aws.amazon.com/kms/pricing), [Amazon CloudWatch pricing](http://aws.amazon.com/cloudwatch/pricing), and [Amazon Elastic Container Registry pricing](http://aws.amazon.com/ecr/pricing).

**Topics**
+ [Run the 'Publish Docker image to Amazon ECR' sample](#sample-docker-running)
+ [Adapt the 'Publish Docker image to Amazon ECR' sample to push to Docker Hub](sample-docker-docker-hub.md)

## Run the 'Publish Docker image to Amazon ECR' sample
<a name="sample-docker-running"></a>

Use the following procedure to run the sample that publishes a Docker image to Amazon ECR. For more infomration about this sample, see ['Publish Docker image to an Amazon ECR image repository' sample for CodeBuild](#sample-docker).

**To run this sample**

1. If you already have an image repository in Amazon ECR you want to use, skip to step 3. Otherwise, if you are using an user instead of an AWS root account or an administrator user to work with Amazon ECR, add this statement (between *\$1\$1\$1 BEGIN ADDING STATEMENT HERE \$1\$1\$1* and *\$1\$1\$1 END ADDING STATEMENT HERE \$1\$1\$1*) to the user (or IAM group the user is associated with). Using an AWS root account is not recommended.This statement allows the creation of Amazon ECR repositories for storing Docker images. Ellipses (`...`) are used for brevity and to help you locate where to add the statement. Do not remove any statements, and do not type these ellipses into the policy. For more information, see [Working with inline policies using the AWS Management Console](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_inline-using.html#AddingPermissions_Console) in the *user Guide*. 

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "ecr:CreateRepository"
               ],
               "Resource": "*"
           }
       ]
   }
   ```

------
**Note**  
The IAM entity that modifies this policy must have permission in IAM to modify policies.

1. Create an image repository in Amazon ECR. Be sure to create the repository in the same AWS Region where you create your build environment and run your build. For more information, see [Creating a repository](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html) in the *Amazon ECR User Guide*. This repository's name must match the repository name you specify later in this procedure, represented by the `IMAGE_REPO_NAME` environment variable. Ensure that the Amazon ECR repository policy grants image push access for your CodeBuild service IAM role. 

1. Add this statement (between *\$1\$1\$1 BEGIN ADDING STATEMENT HERE \$1\$1\$1* and *\$1\$1\$1 END ADDING STATEMENT HERE \$1\$1\$1*) to the policy you attached to your AWS CodeBuild service role. This statement allows CodeBuild to upload Docker images to Amazon ECR repositories. Ellipses (`...`) are used for brevity and to help you locate where to add the statement. Do not remove any statements, and do not type these ellipses into the policy. 

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "ecr:BatchCheckLayerAvailability",
                   "ecr:CompleteLayerUpload",
                   "ecr:GetAuthorizationToken",
                   "ecr:InitiateLayerUpload",
                   "ecr:PutImage",
                   "ecr:UploadLayerPart"
               ],
               "Resource": "*"
           }
       ]
   }
   ```

------
**Note**  
The IAM entity that modifies this policy must have permission in IAM to modify policies.

1. Create the files as described in the [Directory structure](#sample-docker-dir) and [Files](#sample-docker-files) sections of this topic, and then upload them to an S3 input bucket or an AWS CodeCommit, GitHub, or Bitbucket repository. For more information, see [ Image definitions file reference](https://docs.aws.amazon.com/codepipeline/latest/userguide/file-reference.html) in the *AWS CodePipeline User Guide*.
**Important**  
Do not upload `(root directory name)`, just the files inside of `(root directory name)`.   
If you are using an S3 input bucket, be sure to create a ZIP file that contains the files, and then upload it to the input bucket. Do not add `(root directory name)` to the ZIP file, just the files inside of `(root directory name)`.

1. Create a build project, run the build, and view build information.

    If you use the console to create your project:

   1.  For **Operating system**, choose **Ubuntu**. 

   1.  For **Runtime**, choose **Standard**. 

   1.  For **Image**, choose **aws/codebuild/standard:5.0**. 

   1.  Add the following environment variables: 
      +  AWS\$1DEFAULT\$1REGION with a value of *region-ID* 
      +  AWS\$1ACCOUNT\$1ID with a value of *account-ID* 
      +  IMAGE\$1TAG with a value of Latest 
      +  IMAGE\$1REPO\$1NAME with a value of *Amazon-ECR-repo-name* 

   If you use the AWS CLI to create the build project, the JSON-formatted input to the `create-project` command might look similar to this. (Replace the placeholders with your own values.)

   ```
   {
     "name": "sample-docker-project",
     "source": {
       "type": "S3",
       "location": "codebuild-region-ID-account-ID-input-bucket/DockerSample.zip"
     },
     "artifacts": {
       "type": "NO_ARTIFACTS"
     },
     "environment": {
       "type": "LINUX_CONTAINER",
       "image": "aws/codebuild/standard:5.0",
       "computeType": "BUILD_GENERAL1_SMALL",
       "environmentVariables": [
         {
           "name": "AWS_DEFAULT_REGION",
           "value": "region-ID"
         },
         {
           "name": "AWS_ACCOUNT_ID",
           "value": "account-ID"
         },
         {
           "name": "IMAGE_REPO_NAME",
           "value": "Amazon-ECR-repo-name"
         },
         {
           "name": "IMAGE_TAG",
           "value": "latest"
         }
       ],
     },
     "serviceRole": "arn:aws:iam::account-ID:role/role-name",
     "encryptionKey": "arn:aws:kms:region-ID:account-ID:key/key-ID"
   }
   ```

1. Confirm that CodeBuild successfully pushed the Docker image to the repository:

   1. Open the Amazon ECR console at [https://console.aws.amazon.com/ecr/](https://console.aws.amazon.com/ecr/).

   1. Choose the repository name. The image should be listed in the **Image tag** column.

### Directory structure
<a name="sample-docker-dir"></a>

This sample assumes this directory structure.

```
(root directory name)
├── buildspec.yml
└── Dockerfile
```

### Files
<a name="sample-docker-files"></a>

This sample uses these files.

`buildspec.yml` (in `(root directory name)`)

```
version: 0.2

phases:
  pre_build:
    commands:
      - echo Logging in to Amazon ECR...
      - aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com
  build:
    commands:
      - echo Build started on `date`
      - echo Building the Docker image...          
      - docker build -t $IMAGE_REPO_NAME:$IMAGE_TAG .
      - docker tag $IMAGE_REPO_NAME:$IMAGE_TAG $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG      
  post_build:
    commands:
      - echo Build completed on `date`
      - echo Pushing the Docker image...
      - docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG
```

`Dockerfile` (in `(root directory name)`)

```
FROM golang:1.12-alpine AS build
#Install git
RUN apk add --no-cache git
#Get the hello world package from a GitHub repository
RUN go get github.com/golang/example/hello
WORKDIR /go/src/github.com/golang/example/hello
# Build the project and send the output to /bin/HelloWorld 
RUN go build -o /bin/HelloWorld

FROM golang:1.12-alpine
#Copy the build's output binary from the previous build container
COPY --from=build /bin/HelloWorld /bin/HelloWorld
ENTRYPOINT ["/bin/HelloWorld"]
```

**Note**  
CodeBuild overrides the `ENTRYPOINT` for custom Docker images.

# Adapt the 'Publish Docker image to Amazon ECR' sample to push to Docker Hub
<a name="sample-docker-docker-hub"></a>

To adapt the 'Publish Docker image to Amazon ECR' sample so that the Docker image is pushed to Docker Hub instead of Amazon ECR, edit the sample's code. For more information about the sample, see ['Publish Docker image to an Amazon ECR image repository' sample for CodeBuild](sample-docker.md) and [Run the 'Publish Docker image to Amazon ECR' sample](sample-docker.md#sample-docker-running).
**Note**  
If you are using a version of Docker earlier than 17.06, remove the `--no-include-email` option.

1. Replace these Amazon ECR-specific lines of code in the `buildspec.yml` file:

   ```
   ...
     pre_build:
       commands:
         - echo Logging in to Amazon ECR...
         - aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com
     build:
       commands:
         - echo Build started on `date`
         - echo Building the Docker image...          
         - docker build -t $IMAGE_REPO_NAME:$IMAGE_TAG .
         - docker tag $IMAGE_REPO_NAME:$IMAGE_TAG $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG
     post_build:
       commands:
         - echo Build completed on `date`
         - echo Pushing the Docker image...
         - docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG
   ...
   ```

   With these Docker Hub-specific lines of code:

   ```
   ...
     pre_build:
       commands:
         - echo Logging in to Docker Hub...
         # Type the command to log in to your Docker Hub account here.          
     build:
       commands:
         - echo Build started on `date`
         - echo Building the Docker image...
         - docker build -t $IMAGE_REPO_NAME:$IMAGE_TAG .
         - docker tag $IMAGE_REPO_NAME:$IMAGE_TAG $IMAGE_REPO_NAME:$IMAGE_TAG
     post_build:
       commands:
         - echo Build completed on `date`
         - echo Pushing the Docker image...
         - docker push $IMAGE_REPO_NAME:$IMAGE_TAG
   ...
   ```

1. Upload the edited code to an S3 input bucket or an AWS CodeCommit, GitHub, or Bitbucket repository. 
**Important**  
Do not upload `(root directory name)`, just the files inside of `(root directory name)`.   
If you are using an S3 input bucket, be sure to create a ZIP file that contains the files, and then upload it to the input bucket. Do not add `(root directory name)` to the ZIP file, just the files inside of `(root directory name)`.

1. Replace these lines of code from the JSON-formatted input to the `create-project` command:

   ```
   ...
       "environmentVariables": [
         {
           "name": "AWS_DEFAULT_REGION",
           "value": "region-ID"
         },
         {
           "name": "AWS_ACCOUNT_ID",
           "value": "account-ID"
         },
         {
           "name": "IMAGE_REPO_NAME",
           "value": "Amazon-ECR-repo-name"
         },
         {
           "name": "IMAGE_TAG",
           "value": "latest"
         }
       ]
   ...
   ```

   With these lines of code:

   ```
   ...
       "environmentVariables": [
         {
           "name": "IMAGE_REPO_NAME",
           "value": "your-Docker-Hub-repo-name"
         },
         {
           "name": "IMAGE_TAG",
           "value": "latest"
         }
       ]
   ...
   ```

1. Create a build environment, run the build, and view related build information.

1. Confirm that AWS CodeBuild successfully pushed the Docker image to the repository. Sign in to Docker Hub, go to the repository, and choose the **Tags** tab. The `latest` tag should contain a very recent **Last Updated** value.

# Private registry with AWS Secrets Manager sample for CodeBuild
<a name="sample-private-registry"></a>

 This sample shows you how to use a Docker image that is stored in a private registry as your AWS CodeBuild runtime environment. The credentials for the private registry are stored in AWS Secrets Manager. Any private registry works with CodeBuild. This sample uses Docker Hub. 

**Note**  
Secrets are visible to actions and are not masked when written to a file.

**Topics**
+ [Private registry sample requirements](#sample-private-registry-requirements)
+ [Create a CodeBuild project with a private registry](private-registry-sample-create-project.md)
+ [Configure a private registry credential for self-hosted runners](private-registry-sample-configure-runners.md)

## Private registry sample requirements
<a name="sample-private-registry-requirements"></a>

 To use a private registry with AWS CodeBuild, you must have the following: 
+  A Secrets Manager secret that stores your Docker Hub credentials. The credentials are used to access your private repository. 
**Note**  
You will be charged for secrets that you create.
+  A private repository or account. 
+  A CodeBuild service role IAM policy that grants access to your Secrets Manager secret. 

 Follow these steps to create these resources and then create a CodeBuild build project using the Docker images stored in your private registry. 

# Create a CodeBuild project with a private registry
<a name="private-registry-sample-create-project"></a>

1. For information about how to create a free private repository, see [Repositories on Docker Hub](https://docs.docker.com/docker-hub/repos/). You can also run the following commands in a terminal to pull an image, get its ID, and push it to a new repository. 

   ```
   docker pull amazonlinux
   docker images amazonlinux --format {{.ID}}
   docker tag image-id your-username/repository-name:tag
   docker login
   docker push your-username/repository-name
   ```

1.  Follow the steps in [Create an AWS Secrets Manager secret](https://docs.aws.amazon.com/secretsmanager/latest/userguide/create_secret.html) in the *AWS Secrets Manager User Guide*.

   

   1.  In step 3, in **Choose secret type**, choose **Other type of secret**. 

   1. In **Key/value pairs**, create one key-value pair for your Docker Hub user name and one key-value pair for your Docker Hub password. 

   1.  Continue following the steps in [Create an AWS Secrets Manager secret](https://docs.aws.amazon.com/secretsmanager/latest/userguide/create_secret.html). 

   1.  In step 5, on the **Configure automatic rotation** page, turn it off because the keys correspond to your Docker Hub credentials. 

   1.  Finish following the steps in [Create an AWS Secrets Manager secret](https://docs.aws.amazon.com/secretsmanager/latest/userguide/create_secret.html). 

    For more information, see [What is AWS Secrets Manager?](https://docs.aws.amazon.com/secretsmanager/latest/userguide/) 

1.  When you create an AWS CodeBuild project in the console, CodeBuild attaches the required permission for you. If you use an AWS KMS key other than `DefaultEncryptionKey`, you must add it to the service role. For more information, see [Modifying a role (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage_modify.html#roles-managingrole-editing-console) in the *IAM User Guide*. 

    For your service role to work with Secrets Manager, it must have, at a minimum, the `secretsmanager:GetSecretValue` permission.   
![\[The service role configuration.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/private-registry-sample-iam.png)

1.  To use the console to create a project with an environment stored in a private registry, do the following while you create a project. For information, see [Create a build project (console)](create-project.md#create-project-console). 
**Note**  
 If your private registry is in your VPC, it must have public internet access. CodeBuild cannot pull an image from a private IP address in a VPC. 

   1.  In **Environment image**, choose **Custom image**. 

   1.  For **Environment type**, choose **Linux** or **Windows**. 

   1.  For **Image registry**, choose **Other registry**. 

   1.  In **External registry URL**, enter the image location and in **Registry credential - optional** enter the ARN or name of your Secrets Manager credentials.
**Note**  
 If your credentials do not exist in your current Region, then you must use the ARN. You cannot use the credential name if the credentials exist in a different Region. 

# Configure a private registry credential for self-hosted runners
<a name="private-registry-sample-configure-runners"></a>

Use the following instructions to configure a registry credential for a self-hosted runner.

**Note**  
Note that these credentials will only be used if the images are overridden with those from private registries. 

------
#### [ AWS Management Console ]

1. Open the AWS CodeBuild console at [https://console.aws.amazon.com/codesuite/codebuild/home](https://console.aws.amazon.com/codesuite/codebuild/home).

1. Create a build project or select an existing project. For information, see [Create a build project (console)](create-project.md#create-project-console) and [Change a build project's settings (console)](change-project.md#change-project-console).

1.  In **Environment**, choose **Additional configuration**. 

1.  In **Additional configuration**, enter the name or ARN of the secret from AWS Secrets Manager for **Registry credential - optional**.  
![\[The registry credential configuration.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/registry-credential.png)

------
#### [ AWS CLI ]

1. If you'd like to create a new project, run the **create-project** command.

   ```
   aws codebuild create-project \
       --name project-name \
       --source type=source-type,location=source-location \
       --environment "type=environment-type,image=image,computeType=compute-type,registryCredential={credentialProvider=SECRETS_MANAGER,credential=secret-name-or-arn},imagePullCredentialsType=CODEBUILD|SERVICE_ROLE" \
       --artifacts type=artifacts-type \
       --service-role arn:aws:iam::account-ID:role/service-role/service-role-name
   ```

1. If you'd like to update an existing project, run the **update-project** command.

   ```
   aws codebuild update-project \
       --name project-name \
       --environment "type=environment-type,image=image,computeType=compute-type,registryCredential={credentialProvider=SECRETS_MANAGER,credential=secret-name-or-arn}"
   ```

------