

# Run AWS IoT Greengrass Core software in a Docker container
<a name="run-greengrass-docker"></a>

AWS IoT Greengrass can be configured to run in a Docker container. Docker is a platform that provides the tools for you to build, run, test, and deploy applications that are based on Linux containers. When you run an AWS IoT Greengrass Docker image, you can choose whether to provide your AWS credentials to the Docker container and allow the AWS IoT Greengrass Core software installer to automatically provision the AWS resources that a Greengrass core device requires to operate. If you don't want to provide AWS credentials, then you can manually provision AWS resources and run AWS IoT Greengrass Core software in the Docker container.

**Topics**
+ [Supported platforms and requirements](#greengrass-docker-supported-platforms)
+ [Software downloads](#greengrass-docker-downloads)
+ [Choose how to provision AWS resources](#greengrass-docker-resource-provisioning)
+ [Build the AWS IoT Greengrass image from a Dockerfile](build-greengrass-dockerfile.md)
+ [Run AWS IoT Greengrass in Docker with automatic provisioning](run-greengrass-docker-automatic-provisioning.md)
+ [Run AWS IoT Greengrass in Docker with manual provisioning](run-greengrass-docker-manual-provisioning.md)
+ [Troubleshooting AWS IoT Greengrass in a Docker container](docker-troubleshooting.md)

## Supported platforms and requirements
<a name="greengrass-docker-supported-platforms"></a>

Host computers must meet the following minimum requirements to install and run the AWS IoT Greengrass Core software in a Docker container:
+ <a name="docker-host-reqs"></a>A Linux-based operating system with an internet connection.
+ <a name="docker-engine-reqs"></a>[Docker Engine](https://docs.docker.com/engine/install/) version 18.09 or later.
+ <a name="docker-compose-reqs"></a>(Optional) [Docker Compose](https://docs.docker.com/compose/install/) version 1.22 or later. Docker Compose is required only if you want to use the Docker Compose CLI to run your Docker images.

To run Lambda function components inside of the Docker container, you must configure the container to meet additional requirements. For more information, see [Lambda function requirements](setting-up.md#greengrass-v2-lambda-requirements).

### Run components in process mode
<a name="docker-container-mode-limitation"></a>

AWS IoT Greengrass doesn't support running Lambda functions or AWS-provided components in an isolated runtime environment inside the AWS IoT Greengrass Docker container. You must run these components in process mode without any isolation.

When you configure a Lambda function component, set the isolation mode to **No container**. For more information, see [Run AWS Lambda functions](run-lambda-functions.md). 

When you deploy any of the following AWS-provided components, update the configuration for each component to set the `containerMode` parameter to `NoContainer`. For more information about configuration updates, see [Update component configurations](update-component-configurations.md).
+ [CloudWatch metrics](cloudwatch-metrics-component.md)
+ [Device Defender](device-defender-component.md)
+ [Firehose](kinesis-firehose-component.md)
+ [Modbus-RTU protocol adapter](modbus-rtu-protocol-adapter-component.md)
+ [Amazon SNS](sns-component.md)

## AWS IoT Greengrass Docker software downloads
<a name="greengrass-docker-downloads"></a>

AWS IoT Greengrass provides a Dockerfile to build a container image that has AWS IoT Greengrass Core software and dependencies installed on an Amazon Linux 2 (x86\$164) base image. You can modify the base image in the Dockerfile to run AWS IoT Greengrass on a different platform architecture.

Download the Dockerfile package from [GitHub](https://github.com/aws-greengrass/aws-greengrass-docker).

The Dockerfile uses an older version of Greengrass. You should update the file to use the version of Greengrass that you want. For information about building the AWS IoT Greengrass container image from the Dockerfile, see [Build the AWS IoT Greengrass container image from a Dockerfile](build-greengrass-dockerfile.md).

## Choose how to provision AWS resources
<a name="greengrass-docker-resource-provisioning"></a>

When you install the AWS IoT Greengrass Core software in a Docker container, you can choose whether to automatically provision the AWS resources that a Greengrass core device requires to operate, or to use resources that you manually provision.
+ **Automatic resource provisioning**—The installer provisions the AWS IoT thing, AWS IoT thing group, IAM role, and AWS IoT role alias when you run the AWS IoT Greengrass container image for the first time. The installer can also deploy the local development tools to the core device, so you can use the device to develop and test custom software components. To automatically provision these resources, you must provide AWS credentials as environment variables to the Docker image.

  To use automatic provisioning, you must set the Docker environment variable `PROVISION=true` and mount a credential file to provide your AWS credentials to the container.
+ **Manual resource provisioning**—If you don't want to provide AWS credentials to the container, then you can manually provision the AWS resources before you run the AWS IoT Greengrass container image. You must create a configuration file to provide information about these resources to the AWS IoT Greengrass Core software installer within the Docker container.

  To use manual provisioning, you must set the Docker environment variable `PROVISION=false`. Manual provisioning is the default option.

For more information, see [Build the AWS IoT Greengrass container image from a Dockerfile](build-greengrass-dockerfile.md).

# Build the AWS IoT Greengrass container image from a Dockerfile
<a name="build-greengrass-dockerfile"></a>

AWS provides a Dockerfile that you can download and use to run AWS IoT Greengrass Core software in a Docker container. Dockerfiles contain source code for building AWS IoT Greengrass container images. 

Before you build an AWS IoT Greengrass container image, you must configure your Dockerfile to select the version of AWS IoT Greengrass Core software that you want to install. You can also configure environment variables to choose how to provision resources during installation, and customize other installation options. This section describes how to configure and build an AWS IoT Greengrass Docker image from a Dockerfile. 



## Download the Dockerfile package
<a name="download-dockerfile-package"></a>

You can download the AWS IoT Greengrass Dockerfile package from GitHub:

[AWS Greengrass Docker Repository](https://github.com/aws-greengrass/aws-greengrass-docker)

After you download the package, extract the contents to the `download-directory/aws-greengrass-docker-nucleus-version` folder on your computer. The Dockerfile uses an older version of Greengrass. You should update the file to use the version of Greengrass that you want.

## Specify the AWS IoT Greengrass Core software version
<a name="set-dockerfile-build-argument"></a>

Use the following build argument in the Dockerfile to specify the version of the AWS IoT Greengrass Core software that you want to use in the AWS IoT Greengrass Docker image. By default, the Dockerfile uses the latest version of the AWS IoT Greengrass Core software.

`GREENGRASS_RELEASE_VERSION`  
The version of the AWS IoT Greengrass Core software. By default, the Dockerfile downloads the latest available version of the Greengrass nucleus. Set the value to the version of the nucleus that you want to download.

## Set environment variables
<a name="set-dockerfile-environment-variables"></a>

Environment variables enable you to customize how AWS IoT Greengrass Core software is installed in the Docker container. You can set environment variables for your AWS IoT Greengrass Docker image in various ways. 
+ To use the same environment variables to create multiple images, set environment variables directly in the Dockerfile.
+ If you use `docker run` to start your container, pass environment variables as arguments in the command, or set environment variables in an environment variables file and then pass the file as an argument. For more information about setting environment variables in Docker, see the [environment variables](https://docs.docker.com/engine/reference/commandline/run/#env) in the Docker documentation.
+ If you use `docker-compose up` to start your container, set environment variables in an environment variables file and then pass the file as an argument. For more information about setting environment variables in Compose, see the [Docker documentation](https://docs.docker.com/compose/environment-variables/).

You can configure the following environment variables for the AWS IoT Greengrass Docker image.

**Note**  
Don't modify the `TINI_KILL_PROCESS_GROUP` variable in the Dockerfile. This variable allows forwarding `SIGTERM` to all PIDs in the PID group so that AWS IoT Greengrass Core software can shut down correctly when the Docker container is stopped.

`GGC_ROOT_PATH`  
(Optional) The path to the folder within the container to use as the root for AWS IoT Greengrass Core software.  
Default: `/greengrass/v2`

`PROVISION`  
(Optional) Determines whether the AWS IoT Greengrass Core provisions AWS resources.   
+ If you specify `true`, AWS IoT Greengrass Core software registers the container image as an AWS IoT thing and provisions the AWS resources that the Greengrass core device requires. The AWS IoT Greengrass Core software provisions an AWS IoT thing, (optional) an AWS IoT thing group, an IAM role, and an AWS IoT role alias. For more information, see [Run AWS IoT Greengrass in a Docker container with automatic resource provisioning](run-greengrass-docker-automatic-provisioning.md).
+ If you specify `false`, then you must create a configuration file to provide to the AWS IoT Greengrass Core installer that specifies to use the AWS resources and certificates that you manually created. For more information, see [Run AWS IoT Greengrass in a Docker container with manual resource provisioning](run-greengrass-docker-manual-provisioning.md).
Default: `false`

`AWS_REGION`  
(Optional) The AWS Region that the AWS IoT Greengrass Core software uses to retrieve or create required AWS resources.   
Default: `us-east-1`.

`THING_NAME`  
(Optional) The name of the AWS IoT thing that you register as this core device. If the thing with this name doesn't exist in your AWS account, the AWS IoT Greengrass Core software creates it.   
You must specify `PROVISION=true` to apply this argument.  
Default: `GreengrassV2IotThing_` plus a random UUID.

`THING_GROUP_NAME`  
(Optional) The name of the AWS IoT thing group where you add this core device's AWS IoT If a deployment targets this thing group, this and other core devices in that group receive that deployment when it connects to AWS IoT Greengrass. If the thing group with this name doesn't exist in your AWS account, the AWS IoT Greengrass Core software creates it.  
You must specify `PROVISION=true` to apply this argument.

`TES_ROLE_NAME`  
(Optional) The name of the IAM role to use to acquire AWS credentials that let the Greengrass core device interact with AWS services. If the role with this name doesn't exist in your AWS account, the AWS IoT Greengrass Core software creates it with the `GreengrassV2TokenExchangeRoleAccess` policy. This role doesn't have access to your S3 buckets where you host component artifacts. So, you must add permissions to your artifacts' S3 buckets and objects when you create a component. For more information, see [Authorize core devices to interact with AWS services](device-service-role.md).  
Default: `GreengrassV2TokenExchangeRole`

`TES_ROLE_ALIAS_NAME`  
(Optional) The name of the AWS IoT role alias that points to the IAM role that provides AWS credentials for the Greengrass core device. If the role alias with this name doesn't exist in your AWS account, the AWS IoT Greengrass Core software creates it and points it to the IAM role that you specify.  
Default: `GreengrassV2TokenExchangeRoleAlias`

`COMPONENT_DEFAULT_USER`  
(Optional) The name or ID of the system user and group that the AWS IoT Greengrass Core software uses to run components. Specify the user and group, separated by a colon. The group is optional. For example, you can specify **ggc\$1user:ggc\$1group** or **ggc\$1user**.  
+ If you run as root, this defaults to the user and group that the configuration file defines. If the configuration file doesn't define a user and group, this defaults to `ggc_user:ggc_group`. If `ggc_user` or `ggc_group` don't exist, the software creates them.
+ If you run as a non-root user, the AWS IoT Greengrass Core software uses that user to run components.
+ If you don't specify a group, the AWS IoT Greengrass Core software uses the primary group of the system user.
For more information, see [Configure the user that runs components](configure-greengrass-core-v2.md#configure-component-user).

`DEPLOY_DEV_TOOLS`  
Defines whether to download and deploy the [Greengrass CLI component](greengrass-cli-component.md) in the container image. You can use the Greengrass CLI to develop and debug components locally.  
 <a name="local-dev-tools-production-environment-warning"></a>We recommend that you use this component in only development environments, not production environments. This component provides access to information and operations that you typically won't need in a production environment. Follow the principle of least privilege by deploying this component to only core devices where you need it. 
Default: `false`

`INIT_CONFIG`  
(Optional) The path to the configuration file to use to install the AWS IoT Greengrass Core software. You can use this option to set up new Greengrass core devices with a specific nucleus configuration, or to specify manually provisioned resources, for example. You must mount your configuration file to the path that you specify in this argument. 

`TRUSTED_PLUGIN`  
This feature is available for v2.4.0 and later of the [Greengrass nucleus component](greengrass-nucleus-component.md).  
(Optional) The path to a JAR file to load as a trusted plugin. Use this option to provide provisioning plugin JAR files, such as to install with [fleet provisioning](fleet-provisioning.md) or [custom provisioning](custom-provisioning.md). 

`THING_POLICY_NAME`  
This feature is available for v2.4.0 and later of the [Greengrass nucleus component](greengrass-nucleus-component.md).  
(Optional) The name of the AWS IoT policy to attach to this core device's AWS IoT thing certificate. If the AWS IoT policy with this name doesn't exist in your AWS account the AWS IoT Greengrass Core software creates it.   
You must specify `PROVISION=true` to apply this argument.  
The AWS IoT Greengrass Core software creates a permissive AWS IoT policy by default. You can scope down this policy, or create a custom policy where you restrict permissions for your use case. For more information, see [Minimal AWS IoT policy for AWS IoT Greengrass V2 core devices](device-auth.md#greengrass-core-minimal-iot-policy). 

## Specify the dependencies to install
<a name="dockerfile-run-instruction"></a>

The RUN instruction in the AWS IoT Greengrass Dockerfile prepares up the container environment to run the AWS IoT Greengrass Core software installer. You can customize the dependencies that are installed before the AWS IoT Greengrass Core software installer runs in the Docker container. 

## Build the AWS IoT Greengrass image
<a name="build-greengrass-docker-image"></a>

Use the AWS IoT Greengrass Dockerfile to build an AWS IoT Greengrass container image. You can use the Docker CLI or the Docker Compose CLI to build the image and start the container. You can also use the Docker CLI to build the image and then use Docker Compose to start your container from that image.

------
#### [ Docker ]

1. On the host machine, run the following command to switch to the directory that contains the configured Dockerfile.

   ```
   cd download-directory/aws-greengrass-docker-nucleus-version
   ```

1. Run the following command to build the AWS IoT Greengrass container image from the Dockerfile.

   ```
   sudo docker build -t "platform/aws-iot-greengrass:nucleus-version" ./
   ```

------
#### [ Docker Compose ]

1. On the host machine, run the following command to switch to the directory that contains the Dockerfile and the Compose file.

   ```
   cd download-directory/aws-greengrass-docker-nucleus-version
   ```

1. Run the following command to use the Compose file to build the AWS IoT Greengrass container image.

   ```
   docker-compose -f docker-compose.yml build
   ```

------

You have successfully created the AWS IoT Greengrass container image. The Docker image has the AWS IoT Greengrass Core software installed. You can now run the AWS IoT Greengrass Core software in a Docker container.

# Run AWS IoT Greengrass in a Docker container with automatic resource provisioning
<a name="run-greengrass-docker-automatic-provisioning"></a>

This tutorial shows you how to install and run AWS IoT Greengrass Core software in a Docker container with automatically provisioned AWS resources and local development tools. You can use this development environment to explore AWS IoT Greengrass features in a Docker container. The software requires AWS credentials to provision these resources and deploy the local development tools.

If you can't provide AWS credentials to the container, you can provision the AWS resources that the core device requires to operate. You can also deploy the development tools to a core device to use as a development device. This enables you to provide fewer permissions to the device when you run the container. For more information, see [Run AWS IoT Greengrass in a Docker container with manual resource provisioning](run-greengrass-docker-manual-provisioning.md).



## Prerequisites
<a name="docker-automatic-provisioning-prereqs"></a>

To complete this tutorial, you need the following.
+ An AWS account. If you don't have one, see [Set up an AWS account](setting-up.md#set-up-aws-account). 
+ An AWS IAM user with permissions to provision the AWS IoT and IAM resources for a Greengrass core device. The AWS IoT Greengrass Core software installer uses your AWS credentials to automatically provision these resources. For information about the minimal IAM policy to automatically provision resources, see [Minimal IAM policy for installer to provision resources](provision-minimal-iam-policy.md).
+ An AWS IoT Greengrass Docker image. You can [build an image from the AWS IoT Greengrass Dockerfile](build-greengrass-dockerfile.md).
+ The host computer where you run the Docker container must meet the following requirements:
  + <a name="docker-host-reqs"></a>A Linux-based operating system with an internet connection.
  + <a name="docker-engine-reqs"></a>[Docker Engine](https://docs.docker.com/engine/install/) version 18.09 or later.
  + <a name="docker-compose-reqs"></a>(Optional) [Docker Compose](https://docs.docker.com/compose/install/) version 1.22 or later. Docker Compose is required only if you want to use the Docker Compose CLI to run your Docker images.

## Configure your AWS credentials
<a name="configure-aws-credentials-for-docker"></a>

In this step, you create a credential file on the host computer that contains your AWS security credentials. When you run the AWS IoT Greengrass Docker image, you must mount the folder that contains this credential file to `/root/.aws/` in the Docker container. The AWS IoT Greengrass installer uses these credentials to provision resources in your AWS account. For information about the minimal IAM policy that the installer requires to automatically provision resources, see [Minimal IAM policy for installer to provision resources](provision-minimal-iam-policy.md).

1. Retrieve one of the following.
   + Long-term credentials for an IAM user. For information about how to retrieve long-term credentials, see [Managing access keys for IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html) in the *IAM User Guide*.
   + (Recommended) Temporary credentials for an IAM role. For information about how to retrieve temporary credentials, see [Using temporary security credentials with the AWS CLI](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html#using-temp-creds-sdk-cli) in the *IAM User Guide*.

1. Create a folder where you place your credential file.

   ```
   mkdir ./greengrass-v2-credentials
   ```

1. Use a text editor to create a configuration file named `credentials` in the `./greengrass-v2-credentials` folder.

   For example, you can run the following command to use GNU nano to create the `credentials` file. 

   ```
   nano ./greengrass-v2-credentials/credentials
   ```

1. Add your AWS credentials to the `credentials` file in the following format.

   ```
   [default]
   aws_access_key_id = AKIAIOSFODNN7EXAMPLE
   aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
   aws_session_token = AQoEXAMPLEH4aoAH0gNCAPy...truncated...zrkuWJOgQs8IZZaIv2BXIa2R4Olgk
   ```

   Include `aws_session_token` for temporary credentials only.

**Important**  
Remove the credential file from the host computer after you start the AWS IoT Greengrass container. If you don't remove the credential file, then your AWS credentials will remain mounted inside the container. For more information, see [Run the AWS IoT Greengrass Core software in a container](#run-greengrass-image-automatic-provisioning).

## Create an environment file
<a name="create-env-file-automatic-provisioning"></a>

This tutorial uses an environment file to set the environment variables that will be passed to the AWS IoT Greengrass Core software installer inside the Docker container. You can also use [the `-e` or `--env` argument](https://docs.docker.com/engine/reference/commandline/run/#env) in your `docker run` command to set environment variables in the Docker container or you can set the variables in [an `environment` block](https://docs.docker.com/compose/compose-file/compose-file-v3/#environment) in the `docker-compose.yml` file.

1. Use a text editor to create an environment file named `.env`.

   For example, on a Linux-based system, you can run the following command to use GNU nano to create the `.env` in the current directory.

   ```
   nano .env
   ```

1. Copy the following content into the file.

   ```
   GGC_ROOT_PATH=/greengrass/v2
   AWS_REGION=region
   PROVISION=true
   THING_NAME=MyGreengrassCore
   THING_GROUP_NAME=MyGreengrassCoreGroup
   TES_ROLE_NAME=GreengrassV2TokenExchangeRole
   TES_ROLE_ALIAS_NAME=GreengrassCoreTokenExchangeRoleAlias
   COMPONENT_DEFAULT_USER=ggc_user:ggc_group
   ```

   Then, replace the following values.
   + `/greengrass/v2`. The Greengrass root folder that you want to use for installation. You use the `GGC_ROOT` environment variable to set this value.
   + *region*. The AWS Region where you created the resources.
   + *MyGreengrassCore*. The name of the AWS IoT thing. If the thing doesn't exist, the installer creates it. The installer downloads the certificates to authenticate as the AWS IoT thing. 
   + *MyGreengrassCoreGroup*. The name of the AWS IoT thing group. If the thing group doesn't exist, the installer creates it and adds the thing to it. If the thing group exists and has an active deployment, the core device downloads and runs the software that the deployment specifies.
   +  *GreengrassV2TokenExchangeRole*. Replace with the name of the IAM token exchange role that allows the Greengrass core device to get temporary AWS credentials. If the role doesn't exist, the installer creates it and creates and attaches a policy named *GreengrassV2TokenExchangeRole*Access. For more information, see [Authorize core devices to interact with AWS services](device-service-role.md).
   + *GreengrassCoreTokenExchangeRoleAlias*. The token exchange role alias. If the role alias doesn't exist, the installer creates it and points it to the IAM token exchange role that you specify. For more information, see 
**Note**  <a name="docker-local-dev-tools-production-environment-warning"></a>
You can set the `DEPLOY_DEV_TOOLS` environment variable to `true` to deploy the [Greengrass CLI component](greengrass-cli-component.md), which enables you to develop custom components inside of the Docker container. <a name="local-dev-tools-production-environment-warning"></a>We recommend that you use this component in only development environments, not production environments. This component provides access to information and operations that you typically won't need in a production environment. Follow the principle of least privilege by deploying this component to only core devices where you need it. 

## Run the AWS IoT Greengrass Core software in a container
<a name="run-greengrass-image-automatic-provisioning"></a>

This tutorial shows you how to start the Docker image that you built in a the Docker container. You can use the Docker CLI or the Docker Compose CLI to run the AWS IoT Greengrass Core software image in a Docker container. 

------
#### [ Docker ]

1. Run the following command to start the Docker container. 

   ```
   docker run --rm --init -it --name docker-image \
    -v path/to/greengrass-v2-credentials:/root/.aws/:ro \
    --env-file .env \
    -p 8883 \
    your-container-image:version
   ```

   This example command uses the following arguments for [docker run](https://docs.docker.com/engine/reference/commandline/run/):
   + <a name="docker-run-rm"></a>[https://docs.docker.com/engine/reference/run/#clean-up---rm](https://docs.docker.com/engine/reference/run/#clean-up---rm). Cleans up the container when it exits.
   + <a name="docker-run-init"></a>[https://docs.docker.com/engine/reference/run/#specify-an-init-process](https://docs.docker.com/engine/reference/run/#specify-an-init-process). Uses an init process in the container. 
**Note**  
The `--init` argument is required to shut down AWS IoT Greengrass Core software when you stop the Docker container.
   + <a name="docker-run-it"></a>[https://docs.docker.com/engine/reference/run/#foreground](https://docs.docker.com/engine/reference/run/#foreground). (Optional) Runs the Docker container in the foreground as an interactive process. You can replace this with the `-d` argument to run the Docker container in detached mode instead. For more information, see [Detached vs foreground](https://docs.docker.com/engine/reference/run/#detached-vs-foreground) in the Docker documentation.
   + <a name="docker-run-name"></a>[https://docs.docker.com/engine/reference/run/#name---name](https://docs.docker.com/engine/reference/run/#name---name). Runs a container named `aws-iot-greengrass` 
   + <a name="docker-run-v"></a>[https://docs.docker.com/storage/volumes/](https://docs.docker.com/storage/volumes/). Mounts a volume into the Docker container to make the configuration file and the certificate files available to AWS IoT Greengrass running inside the container.
   + <a name="docker-run-env-file"></a>[https://docs.docker.com/engine/reference/commandline/run/#env](https://docs.docker.com/engine/reference/commandline/run/#env). (Optional) Specifies the environment file to set the environment variables that will be passed to the AWS IoT Greengrass Core software installer inside the Docker container. This argument is required only if you created an [environment file](run-greengrass-docker-manual-provisioning.md#create-env-file-manual-provisioning) to set environment variables. If you didn't create an environment file, you can use `--env` arguments to set environment variables directly in your Docker run command.
   + <a name="docker-run-p"></a>[https://docs.docker.com/engine/reference/commandline/run/#publish](https://docs.docker.com/engine/reference/commandline/run/#publish). (Optional) Publishes the 8883 container port to the host machine. This argument is required if you want to connect and communicate over MQTT because AWS IoT Greengrass uses port 8883 for MQTT traffic. To open other ports, use additional `-p` arguments.
**Note**  <a name="docker-run-cap-drop"></a>
To run your Docker container with increased security, you can use the `--cap-drop` and `--cap-add` arguments to selectively enable Linux capabilities for your container. For more information, see [Runtime privilege and Linux capabilities](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) in the Docker documentation.

1. <a name="docker-automatic-provisioning-remove-credentials-file"></a>Remove the credentials from `./greengrass-v2-credentials` on the host device.

   ```
   rm -rf ./greengrass-v2-credentials
   ```
**Important**  
You're removing these credentials, because they provide broad permissions that the core device needs only during setup. If you don't remove these credentials, Greengrass components and other processes running in the container can access them. If you need to provide AWS credentials to a Greengrass component, use the token exchange service. For more information, see [Interact with AWS services](interact-with-aws-services.md).

------
#### [ Docker Compose ]

1. Use a text editor to create a Docker Compose file named `docker-compose.yml`.

   For example, on a Linux-based system, you can run the following command to use GNU nano to create the `docker-compose.yml` in the current directory.

   ```
   nano docker-compose.yml
   ```
**Note**  
You can also download and use the latest version of the AWS-provided Compose file from [GitHub](https://github.com/aws-greengrass/aws-greengrass-docker/releases/).

1. Add the following content to the Compose file. Your file should look similar to the following example. Replace *docker-image* with the name of your Docker image. 

   ```
   version: '3.7'
    
   services:
     greengrass:
       init: true
       container_name: aws-iot-greengrass
       image: docker-image
       volumes:
         - ./greengrass-v2-credentials:/root/.aws/:ro 
       env_file: .env
       ports:
         - "8883:8883"
   ```<a name="docker-compose-optional-params"></a>

   The following parameters in this example Compose file are optional:
   + `ports`—Publishes the 8883 container ports to the host machine. This parameter is required if you want to connect and communicate over MQTT because AWS IoT Greengrass uses port 8883 for MQTT traffic. 
   + `env_file`—Specifies the environment file to set the environment variables that will be passed to the AWS IoT Greengrass Core software installer inside the Docker container. This parameter is required only if you created an [environment file](run-greengrass-docker-manual-provisioning.md#create-env-file-manual-provisioning) to set environment variables. If you didn't create an environment file, you can use the [ environment](https://docs.docker.com/compose/compose-file/compose-file-v3/#environment) parameter to set the variables directly in your Compose file.
**Note**  <a name="docker-compose-cap-drop"></a>
To run your Docker container with increased security, you can use `cap_drop` and `cap_add` in your Compose file to selectively enable Linux capabilities for your container. For more information, see [Runtime privilege and Linux capabilities](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) in the Docker documentation.

1. Run the following command to start the Docker container.

   ```
   docker-compose -f docker-compose.yml up
   ```

1. <a name="docker-automatic-provisioning-remove-credentials-file"></a>Remove the credentials from `./greengrass-v2-credentials` on the host device.

   ```
   rm -rf ./greengrass-v2-credentials
   ```
**Important**  
You're removing these credentials, because they provide broad permissions that the core device needs only during setup. If you don't remove these credentials, Greengrass components and other processes running in the container can access them. If you need to provide AWS credentials to a Greengrass component, use the token exchange service. For more information, see [Interact with AWS services](interact-with-aws-services.md).

------

## Next steps
<a name="run-greengrass-docker-next-steps"></a>

<a name="run-greengrass-docker-success"></a>AWS IoT Greengrass Core software is now running in a Docker container. Run the following command to retrieve the container ID for the currently running container.

```
docker ps
```

You can then run the following command to access the container and explore AWS IoT Greengrass Core software running inside the container.

```
docker exec -it container-id /bin/bash
```

For information about creating a simple component, see [Step 4: Develop and test a component on your device](create-first-component.md) in [Tutorial: Getting started with AWS IoT Greengrass V2](getting-started.md)

**Note**  <a name="run-greengrass-commands-in-docker-note"></a>
When you use `docker exec` to run commands inside the Docker container, those commands are not logged in the Docker logs. To log your commands in the Docker logs, attach an interactive shell to the Docker container. For more information, see [Attach an interactive shell to the Docker container](docker-troubleshooting.md#debugging-docker-attach-shell).

The AWS IoT Greengrass Core log file is called `greengrass.log` and is located in `/greengrass/v2/logs`. Component log files are also located in the same directory. To copy Greengrass logs to a temporary directory on the host, run the following command:

```
docker cp container-id:/greengrass/v2/logs /tmp/logs
```

If you want to persist logs after a container exits or has been removed, we recommend that you bind-mount only the `/greengrass/v2/logs` directory to the temporary logs directory on the host instead of mounting the entire Greengrass directory. For more information, see [Persist Greengrass logs outside of the Docker container](docker-troubleshooting.md#debugging-docker-persist-logs).

<a name="greengrass-docker-stop"></a>To stop a running AWS IoT Greengrass Docker container, run `docker stop` or `docker-compose -f docker-compose.yml stop`. This action sends `SIGTERM` to the Greengrass process and shuts down all associated processes that were started in the container. The Docker container is initialized with the `docker-init` executable as process PID 1, which helps in removing any leftover zombie processes. For more information, see the [Specify an init process](https://docs.docker.com/engine/reference/run/#specify-an-init-process) in the Docker documentation.

<a name="see-docker-troubleshooting"></a>For information about troubleshooting issues with running AWS IoT Greengrass in a Docker container, see [Troubleshooting AWS IoT Greengrass in a Docker container](docker-troubleshooting.md).

# Run AWS IoT Greengrass in a Docker container with manual resource provisioning
<a name="run-greengrass-docker-manual-provisioning"></a>

This tutorial shows you how to install and run AWS IoT Greengrass Core software in Docker container with manually provisioned AWS resources.

**Topics**
+ [Prerequisites](#docker-manual-provisioning-prereqs)
+ [Retrieve AWS IoT endpoints](#retrieve-iot-endpoints)
+ [Create an AWS IoT thing](#create-iot-thing)
+ [Create the thing certificate](#create-thing-certificate-mp)
+ [Create a token exchange role](#create-token-exchange-role)
+ [Download certificates to the device](#download-thing-certificates)
+ [Create a configuration file](#create-docker-install-configuration-file)
+ [Create an environment file](#create-env-file-manual-provisioning)
+ [Run the AWS IoT Greengrass Core software in a container](#run-greengrass-image-manual-provisioning)
+ [Next steps](#run-greengrass-docker-next-steps)

## Prerequisites
<a name="docker-manual-provisioning-prereqs"></a>

To complete this tutorial, you need the following:
+ An AWS account. If you don't have one, see [Set up an AWS account](setting-up.md#set-up-aws-account). 
+ An AWS IoT Greengrass Docker image. You can [build an image from the AWS IoT Greengrass Dockerfile](build-greengrass-dockerfile.md).
+ The host computer where you run the Docker container must meet the following requirements:
  + <a name="docker-host-reqs"></a>A Linux-based operating system with an internet connection.
  + <a name="docker-engine-reqs"></a>[Docker Engine](https://docs.docker.com/engine/install/) version 18.09 or later.
  + <a name="docker-compose-reqs"></a>(Optional) [Docker Compose](https://docs.docker.com/compose/install/) version 1.22 or later. Docker Compose is required only if you want to use the Docker Compose CLI to run your Docker images.

## Retrieve AWS IoT endpoints
<a name="retrieve-iot-endpoints"></a>

Get the AWS IoT endpoints for your AWS account, and save them to use later. Your device uses these endpoints to connect to AWS IoT. Do the following:

1. Get the AWS IoT data endpoint for your AWS account.

   ```
   aws iot describe-endpoint --endpoint-type iot:Data-ATS
   ```

   The response looks similar to the following example, if the request succeeds.

   ```
   {
     "endpointAddress": "device-data-prefix-ats.iot.us-west-2.amazonaws.com"
   }
   ```

1. Get the AWS IoT credentials endpoint for your AWS account.

   ```
   aws iot describe-endpoint --endpoint-type iot:CredentialProvider
   ```

   The response looks similar to the following example, if the request succeeds.

   ```
   {
     "endpointAddress": "device-credentials-prefix.credentials.iot.us-west-2.amazonaws.com"
   }
   ```

## Create an AWS IoT thing
<a name="create-iot-thing"></a>

AWS IoT *things* represent devices and logical entities that connect to AWS IoT. Greengrass core devices are AWS IoT things. When you register a device as an AWS IoT thing, that device can use a digital certificate to authenticate with AWS.

In this section, you create an AWS IoT thing that represents your device.

**To create an AWS IoT thing**

1. Create an AWS IoT thing for your device. On your development computer, run the following command.
   + Replace *MyGreengrassCore* with the thing name to use. This name is also the name of your Greengrass core device.
**Note**  <a name="install-argument-thing-name-constraint"></a>
The thing name can't contain colon (`:`) characters.

   ```
   aws iot create-thing --thing-name MyGreengrassCore
   ```

   The response looks similar to the following example, if the request succeeds.

   ```
   {
     "thingName": "MyGreengrassCore",
     "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/MyGreengrassCore",
     "thingId": "8cb4b6cd-268e-495d-b5b9-1713d71dbf42"
   }
   ```

1. (Optional) Add the AWS IoT thing to a new or existing thing group. You use thing groups to manage fleets of Greengrass core devices. When you deploy software components to your devices, you can target individual devices or groups of devices. You can add a device to a thing group with an active Greengrass deployment to deploy that thing group's software components to the device. Do the following:

   1. (Optional) Create an AWS IoT thing group.
      + Replace *MyGreengrassCoreGroup* with the name of the thing group to create.
**Note**  <a name="install-argument-thing-group-name-constraint"></a>
The thing group name can't contain colon (`:`) characters.

      ```
      aws iot create-thing-group --thing-group-name MyGreengrassCoreGroup
      ```

      The response looks similar to the following example, if the request succeeds.

      ```
      {
        "thingGroupName": "MyGreengrassCoreGroup",
        "thingGroupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/MyGreengrassCoreGroup",
        "thingGroupId": "4df721e1-ff9f-4f97-92dd-02db4e3f03aa"
      }
      ```

   1. Add the AWS IoT thing to a thing group.
      + Replace *MyGreengrassCore* with the name of your AWS IoT thing.
      + Replace *MyGreengrassCoreGroup* with the name of the thing group.

      ```
      aws iot add-thing-to-thing-group --thing-name MyGreengrassCore --thing-group-name MyGreengrassCoreGroup
      ```

      The command doesn't have any output if the request succeeds.

## Create the thing certificate
<a name="create-thing-certificate-mp"></a>

<a name="create-thing-certificate-intro-1"></a>When you register a device as an AWS IoT thing, that device can use a digital certificate to authenticate with AWS. This certificate allows the device to communicate with AWS IoT and AWS IoT Greengrass.

<a name="create-thing-certificate-intro-2"></a>In this section, you create and download certificates that your device can use to connect to AWS.<a name="create-thing-certificate-cloud-steps"></a>

**To create the thing certificate**

1. Create a folder where you download the certificates for the AWS IoT thing.

   ```
   mkdir greengrass-v2-certs
   ```

1. Create and download the certificates for the AWS IoT thing.

   ```
   aws iot create-keys-and-certificate --set-as-active --certificate-pem-outfile greengrass-v2-certs/device.pem.crt --public-key-outfile greengrass-v2-certs/public.pem.key --private-key-outfile greengrass-v2-certs/private.pem.key
   ```

   The response looks similar to the following example, if the request succeeds.

   ```
   {
     "certificateArn": "arn:aws:iot:us-west-2:123456789012:cert/aa0b7958770878eabe251d8a7ddd547f4889c524c9b574ab9fbf65f32248b1d4",
     "certificateId": "aa0b7958770878eabe251d8a7ddd547f4889c524c9b574ab9fbf65f32248b1d4",
     "certificatePem": "-----BEGIN CERTIFICATE-----
   MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w
    0BAQUFADCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZ
    WF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIw
    EAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5
    jb20wHhcNMTEwNDI1MjA0NTIxWhcNMTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBh
    MCVVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBb
    WF6b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMx
    HzAdBgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wgZ8wDQYJKoZIhvcNAQE
    BBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ21uUSfwfEvySWtC2XADZ4nB+BLYgVI
    k60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9TrDHudUZg3qX4waLG5M43q7Wgc/MbQ
    ITxOUSQv7c7ugFFDzQGBzZswY6786m86gpEIbb3OhjZnzcvQAaRHhdlQWIMm2nr
    AgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4nUhVVxYUntneD9+h8Mg9q6q+auN
    KyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0FkbFFBjvSfpJIlJ00zbhNYS5f6Guo
    EDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTbNYiytVbZPQUQ5Yaxu2jXnimvw
    3rrszlaEXAMPLE=
   -----END CERTIFICATE-----",
     "keyPair": {
       "PublicKey": "-----BEGIN PUBLIC KEY-----\
   MIIBIjANBgkqhkEXAMPLEQEFAAOCAQ8AMIIBCgKCAQEAEXAMPLE1nnyJwKSMHw4h\
   MMEXAMPLEuuN/dMAS3fyce8DW/4+EXAMPLEyjmoF/YVF/gHr99VEEXAMPLE5VF13\
   59VK7cEXAMPLE67GK+y+jikqXOgHh/xJTwo+sGpWEXAMPLEDz18xOd2ka4tCzuWEXAMPLEahJbYkCPUBSU8opVkR7qkEXAMPLE1DR6sx2HocliOOLtu6Fkw91swQWEXAMPLE\\GB3ZPrNh0PzQYvjUStZeccyNCx2EXAMPLEvp9mQOUXP6plfgxwKRX2fEXAMPLEDa\
   hJLXkX3rHU2xbxJSq7D+XEXAMPLEcw+LyFhI5mgFRl88eGdsAEXAMPLElnI9EesG\
   FQIDAQAB\
   -----END PUBLIC KEY-----\
   ",
       "PrivateKey": "-----BEGIN RSA PRIVATE KEY-----\
   key omitted for security reasons\
   -----END RSA PRIVATE KEY-----\
   "
     }
   }
   ```

   Save the certificate's Amazon Resource Name (ARN) to use to configure the certificate later.

Next, configure the thing certificate. For more information, see [Configure the thing certificate](manual-installation.md#configure-thing-certificate).

## Create a token exchange role
<a name="create-token-exchange-role"></a>

<a name="installation-create-token-exchange-role-intro"></a>Greengrass core devices use an IAM service role, called the *token exchange role*, to authorize calls to AWS services. The device uses the AWS IoT credentials provider to get temporary AWS credentials for this role, which allows the device to interact with AWS IoT, send logs to Amazon CloudWatch Logs, and download custom component artifacts from Amazon S3. For more information, see [Authorize core devices to interact with AWS services](device-service-role.md).

<a name="installation-create-token-exchange-role-alias-intro"></a>You use an AWS IoT *role alias* to configure the token exchange role for Greengrass core devices. Role aliases enable you to change the token exchange role for a device but keep the device configuration the same. For more information, see [Authorizing direct calls to AWS services](https://docs.aws.amazon.com/iot/latest/developerguide/authorizing-direct-aws.html) in the *AWS IoT Core Developer Guide*.

In this section, you create a token exchange IAM role and an AWS IoT role alias that points to the role. If you have already set up a Greengrass core device, you can use its token exchange role and role alias instead of creating new ones. Then, you configure your device's AWS IoT thing to use that role and alias.

**To create a token exchange IAM role**

1. <a name="create-token-exchange-role-create-iam-role"></a>Create an IAM role that your device can use as a token exchange role. Do the following:

   1. Create a file that contains the trust policy document that the token exchange role requires.

      <a name="nano-command-intro"></a>For example, on a Linux-based system, you can run the following command to use GNU nano to create the file.

      ```
      nano device-role-trust-policy.json
      ```

      Copy the following JSON into the file.

      ```
      {
        "Version": "2012-10-17",		 	 	 
        "Statement": [
          {
            "Effect": "Allow",
            "Principal": {
              "Service": "credentials.iot.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
          }
        ]
      }
      ```

   1. Create the token exchange role with the trust policy document.
      + Replace *GreengrassV2TokenExchangeRole* with the name of the IAM role to create.

      ```
      aws iam create-role --role-name GreengrassV2TokenExchangeRole --assume-role-policy-document file://device-role-trust-policy.json
      ```

      The response looks similar to the following example, if the request succeeds.

      ```
      {
        "Role": {
          "Path": "/",
          "RoleName": "GreengrassV2TokenExchangeRole",
          "RoleId": "AROAZ2YMUHYHK5OKM77FB",
          "Arn": "arn:aws:iam::123456789012:role/GreengrassV2TokenExchangeRole",
          "CreateDate": "2021-02-06T00:13:29+00:00",
          "AssumeRolePolicyDocument": {
            "Version": "2012-10-17",		 	 	 
            "Statement": [
              {
                "Effect": "Allow",
                "Principal": {
                  "Service": "credentials.iot.amazonaws.com"
                },
                "Action": "sts:AssumeRole"
              }
            ]
          }
        }
      ```

   1. Create a file that contains the access policy document that the token exchange role requires.

      <a name="nano-command-intro"></a>For example, on a Linux-based system, you can run the following command to use GNU nano to create the file.

      ```
      nano device-role-access-policy.json
      ```

      Copy the following JSON into the file.

      ```
      {
        "Version": "2012-10-17",		 	 	 
        "Statement": [
          {
            "Effect": "Allow",
            "Action": [
              "logs:CreateLogGroup",
              "logs:CreateLogStream",
              "logs:PutLogEvents",
              "logs:DescribeLogStreams",
              "s3:GetBucketLocation"
            ],
            "Resource": "*"
          }
        ]
      }
      ```
**Note**  
This access policy doesn't allow access to component artifacts in S3 buckets. To deploy custom components that define artifacts in Amazon S3, you must add permissions to the role to allow your core device to retrieve component artifacts. For more information, see [Allow access to S3 buckets for component artifacts](device-service-role.md#device-service-role-access-s3-bucket).  
If you don't yet have an S3 bucket for component artifacts, you can add these permissions later after you create a bucket.

   1. Create the IAM policy from the policy document.
      + Replace *GreengrassV2TokenExchangeRoleAccess* with the name of the IAM policy to create.

      ```
      aws iam create-policy --policy-name GreengrassV2TokenExchangeRoleAccess --policy-document file://device-role-access-policy.json
      ```

      The response looks similar to the following example, if the request succeeds.

      ```
      {
        "Policy": {
          "PolicyName": "GreengrassV2TokenExchangeRoleAccess",
          "PolicyId": "ANPAZ2YMUHYHACI7C5Z66",
          "Arn": "arn:aws:iam::123456789012:policy/GreengrassV2TokenExchangeRoleAccess",
          "Path": "/",
          "DefaultVersionId": "v1",
          "AttachmentCount": 0,
          "PermissionsBoundaryUsageCount": 0,
          "IsAttachable": true,
          "CreateDate": "2021-02-06T00:37:17+00:00",
          "UpdateDate": "2021-02-06T00:37:17+00:00"
        }
      }
      ```

   1. Attach the IAM policy to the token exchange role.
      + Replace *GreengrassV2TokenExchangeRole* with the name of the IAM role.
      + Replace the policy ARN with the ARN of the IAM policy that you created in the previous step.

      ```
      aws iam attach-role-policy --role-name GreengrassV2TokenExchangeRole --policy-arn arn:aws:iam::123456789012:policy/GreengrassV2TokenExchangeRoleAccess
      ```

      The command doesn't have any output if the request succeeds.

1. <a name="create-token-exchange-role-create-iot-role-alias"></a>Create an AWS IoT role alias that points to the token exchange role.
   + Replace *GreengrassCoreTokenExchangeRoleAlias* with the name of the role alias to create.
   + Replace the role ARN with the ARN of the IAM role that you created in the previous step.

   ```
   aws iot create-role-alias --role-alias GreengrassCoreTokenExchangeRoleAlias --role-arn arn:aws:iam::123456789012:role/GreengrassV2TokenExchangeRole
   ```

   The response looks similar to the following example, if the request succeeds.

   ```
   {
     "roleAlias": "GreengrassCoreTokenExchangeRoleAlias",
     "roleAliasArn": "arn:aws:iot:us-west-2:123456789012:rolealias/GreengrassCoreTokenExchangeRoleAlias"
   }
   ```
**Note**  
To create a role alias, you must have permission to pass the token exchange IAM role to AWS IoT. If you receive an error message when you try to create a role alias, check that your AWS user has this permission. For more information, see [Granting a user permissions to pass a role to an AWS service](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_passrole.html) in the *AWS Identity and Access Management User Guide*.

1. Create and attach an AWS IoT policy that allows your Greengrass core device to use the role alias to assume the token exchange role. If you have set up a Greengrass core device before, you can attach its role alias AWS IoT policy instead of creating a new one. Do the following:

   1. (Optional) Create a file that contains the AWS IoT policy document that the role alias requires.

      <a name="nano-command-intro"></a>For example, on a Linux-based system, you can run the following command to use GNU nano to create the file.

      ```
      nano greengrass-v2-iot-role-alias-policy.json
      ```

      Copy the following JSON into the file.
      + Replace the resource ARN with the ARN of your role alias.

      ```
      {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
          {
            "Effect": "Allow",
            "Action": "iot:AssumeRoleWithCertificate",
            "Resource": "arn:aws:iot:us-west-2:123456789012:rolealias/GreengrassCoreTokenExchangeRoleAlias"
          }
        ]
      }
      ```

   1. Create an AWS IoT policy from the policy document.
      + Replace *GreengrassCoreTokenExchangeRoleAliasPolicy* with the name of the AWS IoT policy to create.

      ```
      aws iot create-policy --policy-name GreengrassCoreTokenExchangeRoleAliasPolicy --policy-document file://greengrass-v2-iot-role-alias-policy.json
      ```

      The response looks similar to the following example, if the request succeeds.

      ```
      {
        "policyName": "GreengrassCoreTokenExchangeRoleAliasPolicy",
        "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/GreengrassCoreTokenExchangeRoleAliasPolicy",
        "policyDocument": "{
          \\"Version\\":\\"2012-10-17		 	 	 \\",
          \\"Statement\\": [
            {
              \\"Effect\\": \\"Allow\\",
              \\"Action\\": \\"iot:AssumeRoleWithCertificate\\",
              \\"Resource\\": \\"arn:aws:iot:us-west-2:123456789012:rolealias/GreengrassCoreTokenExchangeRoleAlias\\"
            }
          ]
        }",
        "policyVersionId": "1"
      }
      ```

   1. Attach the AWS IoT policy to the AWS IoT thing's certificate.
      + Replace *GreengrassCoreTokenExchangeRoleAliasPolicy* with the name of the role alias AWS IoT policy.
      + Replace the target ARN with the ARN of the certificate for your AWS IoT thing.

      ```
      aws iot attach-policy --policy-name GreengrassCoreTokenExchangeRoleAliasPolicy --target arn:aws:iot:us-west-2:123456789012:cert/aa0b7958770878eabe251d8a7ddd547f4889c524c9b574ab9fbf65f32248b1d4
      ```

      The command doesn't have any output if the request succeeds.

## Download certificates to the device
<a name="download-thing-certificates"></a>

Earlier, you downloaded your device's certificate to your development computer. In this section, you download the Amazon root certificate authority (CA) certificate. Then, if you plan to run the AWS IoT Greengrass Core software in Docker on a different computer than your development computer, you copy the certificates to that host computer. The AWS IoT Greengrass Core software uses these certificates to connect to the AWS IoT cloud service.

**To download certificates to the device**

1. On your development computer, download the Amazon root certificate authority (CA) certificate. AWS IoT certificates are associated with Amazon's root CA certificate by default.

------
#### [ Linux or Unix ]

   ```
   sudo curl -o ./greengrass-v2-certs/AmazonRootCA1.pem https://www.amazontrust.com/repository/AmazonRootCA1.pem
   ```

------
#### [ Windows Command Prompt (CMD) ]

   ```
   curl -o .\greengrass-v2-certs\AmazonRootCA1.pem https://www.amazontrust.com/repository/AmazonRootCA1.pem
   ```

------
#### [ PowerShell ]

   ```
   iwr -Uri https://www.amazontrust.com/repository/AmazonRootCA1.pem -OutFile .\greengrass-v2-certs\AmazonRootCA1.pem
   ```

------

1. If you plan to run the AWS IoT Greengrass Core software in Docker on a different device than your development computer, copy the certificates to the host computer. If SSH and SCP are enabled on the development computer and the host computer, you can use the `scp` command on your development computer to transfer the certificates. Replace *device-ip-address* with the IP address of your host computer.

   ```
   scp -r greengrass-v2-certs/ device-ip-address:~
   ```

## Create a configuration file
<a name="create-docker-install-configuration-file"></a>

1. On the host computer, create a folder where you place your configuration file.

   ```
   mkdir ./greengrass-v2-config
   ```

1. Use a text editor to create a configuration file named `config.yaml` in the `./greengrass-v2-config` folder.

   For example, you can run the following command to use GNU nano to create the `config.yaml`. 

   ```
   nano ./greengrass-v2-config/config.yaml
   ```

1. Copy the following YAML content into the file. This partial configuration file specifies system parameters and Greengrass nucleus parameters.

   ```
   ---
   system:
     certificateFilePath: "/tmp/certs/device.pem.crt"
     privateKeyPath: "/tmp/certs/private.pem.key"
     rootCaPath: "/tmp/certs/AmazonRootCA1.pem"
     rootpath: "/greengrass/v2"
     thingName: "MyGreengrassCore"
   services:
     aws.greengrass.Nucleus:
       componentType: "NUCLEUS"
       version: "nucleus-version"
       configuration:
         awsRegion: "region"
         iotRoleAlias: "GreengrassCoreTokenExchangeRoleAlias"
         iotDataEndpoint: "device-data-prefix-ats.iot.region.amazonaws.com"
         iotCredEndpoint: "device-credentials-prefix.credentials.region.amazonaws.com"
   ```

   Then, replace the following values:
   + */tmp/certs*. The directory in the Docker container to which you mount the downloaded certificates when you start the container.
   + `/greengrass/v2`. The Greengrass root folder that you want to use for installation. You use the `GGC_ROOT` environment variable to set this value.
   + *MyGreengrassCore*. The name of the AWS IoT thing.
   + *nucleus-version*. The version of the AWS IoT Greengrass Core software to install. This value must match the version of the Docker image or Dockerfile that you downloaded. If you downloaded the Greengrass Docker image with the `latest` tag, use ****docker inspect *image-id***** to see the image version.
   + *region*. The AWS Region where you created your AWS IoT resources. You must also specify the same value for the `AWS_REGION` environment variable in your [environment file](#create-env-file-manual-provisioning).
   + *GreengrassCoreTokenExchangeRoleAlias*. The token exchange role alias.
   + *device-data-prefix*. The prefix for your AWS IoT data endpoint.
   + *device-credentials-prefix*. The prefix for your AWS IoT credentials endpoint.

## Create an environment file
<a name="create-env-file-manual-provisioning"></a>

This tutorial uses an environment file to set the environment variables that will be passed to the AWS IoT Greengrass Core software installer inside the Docker container. You can also use [the `-e` or `--env` argument](https://docs.docker.com/engine/reference/commandline/run/#env) in your `docker run` command to set environment variables in the Docker container or you can set the variables in [an `environment` block](https://docs.docker.com/compose/compose-file/compose-file-v3/#environment) in the `docker-compose.yml` file.

1. Use a text editor to create an environment file named `.env`.

   For example, on a Linux-based system, you can run the following command to use GNU nano to create the `.env` in the current directory.

   ```
   nano .env
   ```

1. Copy the following content into the file.

   ```
   GGC_ROOT_PATH=/greengrass/v2
   AWS_REGION=region
   PROVISION=false
   COMPONENT_DEFAULT_USER=ggc_user:ggc_group
   INIT_CONFIG=/tmp/config/config.yaml
   ```

   Then, replace the following values.
   + `/greengrass/v2`. The path to the root folder to use to install the AWS IoT Greengrass Core software.
   + *region*. The AWS Region where you created your AWS IoT resources. You must specify the same value for the `awsRegion` configuration parameter in your [configuration file](#create-docker-install-configuration-file).
   + */tmp/config/*. The folder where you mount the configuration file when you start the Docker container.
**Note**  <a name="docker-local-dev-tools-production-environment-warning"></a>
You can set the `DEPLOY_DEV_TOOLS` environment variable to `true` to deploy the [Greengrass CLI component](greengrass-cli-component.md), which enables you to develop custom components inside of the Docker container. <a name="local-dev-tools-production-environment-warning"></a>We recommend that you use this component in only development environments, not production environments. This component provides access to information and operations that you typically won't need in a production environment. Follow the principle of least privilege by deploying this component to only core devices where you need it. 

## Run the AWS IoT Greengrass Core software in a container
<a name="run-greengrass-image-manual-provisioning"></a>

This tutorial shows you how to start the Docker image that you built in a Docker container. You can use the Docker CLI or the Docker Compose CLI to run the AWS IoT Greengrass Core software image in a Docker container. 

------
#### [ Docker ]
+ This tutorial shows you how to start the Docker image that you built in a the Docker container. 

  ```
  docker run --rm --init -it --name docker-image \
   -v path/to/greengrass-v2-config:/tmp/config/:ro \
   -v path/to/greengrass-v2-certs:/tmp/certs:ro \ 
   --env-file .env \
   -p 8883 \
   your-container-image:version
  ```

  This example command uses the following arguments for [docker run](https://docs.docker.com/engine/reference/commandline/run/):
  + <a name="docker-run-rm"></a>[https://docs.docker.com/engine/reference/run/#clean-up---rm](https://docs.docker.com/engine/reference/run/#clean-up---rm). Cleans up the container when it exits.
  + <a name="docker-run-init"></a>[https://docs.docker.com/engine/reference/run/#specify-an-init-process](https://docs.docker.com/engine/reference/run/#specify-an-init-process). Uses an init process in the container. 
**Note**  
The `--init` argument is required to shut down AWS IoT Greengrass Core software when you stop the Docker container.
  + <a name="docker-run-it"></a>[https://docs.docker.com/engine/reference/run/#foreground](https://docs.docker.com/engine/reference/run/#foreground). (Optional) Runs the Docker container in the foreground as an interactive process. You can replace this with the `-d` argument to run the Docker container in detached mode instead. For more information, see [Detached vs foreground](https://docs.docker.com/engine/reference/run/#detached-vs-foreground) in the Docker documentation.
  + <a name="docker-run-name"></a>[https://docs.docker.com/engine/reference/run/#name---name](https://docs.docker.com/engine/reference/run/#name---name). Runs a container named `aws-iot-greengrass` 
  + <a name="docker-run-v"></a>[https://docs.docker.com/storage/volumes/](https://docs.docker.com/storage/volumes/). Mounts a volume into the Docker container to make the configuration file and the certificate files available to AWS IoT Greengrass running inside the container.
  + <a name="docker-run-env-file"></a>[https://docs.docker.com/engine/reference/commandline/run/#env](https://docs.docker.com/engine/reference/commandline/run/#env). (Optional) Specifies the environment file to set the environment variables that will be passed to the AWS IoT Greengrass Core software installer inside the Docker container. This argument is required only if you created an [environment file](#create-env-file-manual-provisioning) to set environment variables. If you didn't create an environment file, you can use `--env` arguments to set environment variables directly in your Docker run command.
  + <a name="docker-run-p"></a>[https://docs.docker.com/engine/reference/commandline/run/#publish](https://docs.docker.com/engine/reference/commandline/run/#publish). (Optional) Publishes the 8883 container port to the host machine. This argument is required if you want to connect and communicate over MQTT because AWS IoT Greengrass uses port 8883 for MQTT traffic. To open other ports, use additional `-p` arguments.
**Note**  <a name="docker-run-cap-drop"></a>
To run your Docker container with increased security, you can use the `--cap-drop` and `--cap-add` arguments to selectively enable Linux capabilities for your container. For more information, see [Runtime privilege and Linux capabilities](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) in the Docker documentation.

------
#### [ Docker Compose ]

1. Use a text editor to create a Docker Compose file named `docker-compose.yml`.

   For example, on a Linux-based system, you can run the following command to use GNU nano to create the `docker-compose.yml` in the current directory.

   ```
   nano docker-compose.yml
   ```
**Note**  
You can also download and use the latest version of the AWS-provided Compose file from [GitHub](https://github.com/aws-greengrass/aws-greengrass-docker/releases/).

1. Add the following content to the Compose file. Your file should look similar to the following example. Replace *your-container-name:version* with the name of your Docker image. 

   ```
   version: '3.7'
    
   services:
     greengrass:
       init: true
       build:
         context: .
       container_name: aws-iot-greengrass
       image: your-container-name:version
       volumes:
         - /path/to/greengrass-v2-config:/tmp/config/:ro
         - /path/to/greengrass-v2-certs:/tmp/certs:ro 
       env_file: .env
       ports:
         - "8883:8883"
   ```<a name="docker-compose-optional-params"></a>

   The following parameters in this example Compose file are optional:
   + `ports`—Publishes the 8883 container ports to the host machine. This parameter is required if you want to connect and communicate over MQTT because AWS IoT Greengrass uses port 8883 for MQTT traffic. 
   + `env_file`—Specifies the environment file to set the environment variables that will be passed to the AWS IoT Greengrass Core software installer inside the Docker container. This parameter is required only if you created an [environment file](#create-env-file-manual-provisioning) to set environment variables. If you didn't create an environment file, you can use the [ environment](https://docs.docker.com/compose/compose-file/compose-file-v3/#environment) parameter to set the variables directly in your Compose file.
**Note**  <a name="docker-compose-cap-drop"></a>
To run your Docker container with increased security, you can use `cap_drop` and `cap_add` in your Compose file to selectively enable Linux capabilities for your container. For more information, see [Runtime privilege and Linux capabilities](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) in the Docker documentation.

1. Run the following command to start the container.

   ```
   docker-compose -f docker-compose.yml up
   ```

------

## Next steps
<a name="run-greengrass-docker-next-steps"></a>

<a name="run-greengrass-docker-success"></a>AWS IoT Greengrass Core software is now running in a Docker container. Run the following command to retrieve the container ID for the currently running container.

```
docker ps
```

You can then run the following command to access the container and explore AWS IoT Greengrass Core software running inside the container.

```
docker exec -it container-id /bin/bash
```

For information about creating a simple component, see [Step 4: Develop and test a component on your device](create-first-component.md) in [Tutorial: Getting started with AWS IoT Greengrass V2](getting-started.md)

**Note**  <a name="run-greengrass-commands-in-docker-note"></a>
When you use `docker exec` to run commands inside the Docker container, those commands are not logged in the Docker logs. To log your commands in the Docker logs, attach an interactive shell to the Docker container. For more information, see [Attach an interactive shell to the Docker container](docker-troubleshooting.md#debugging-docker-attach-shell).

The AWS IoT Greengrass Core log file is called `greengrass.log` and is located in `/greengrass/v2/logs`. Component log files are also located in the same directory. To copy Greengrass logs to a temporary directory on the host, run the following command:

```
docker cp container-id:/greengrass/v2/logs /tmp/logs
```

If you want to persist logs after a container exits or has been removed, we recommend that you bind-mount only the `/greengrass/v2/logs` directory to the temporary logs directory on the host instead of mounting the entire Greengrass directory. For more information, see [Persist Greengrass logs outside of the Docker container](docker-troubleshooting.md#debugging-docker-persist-logs).

<a name="greengrass-docker-stop"></a>To stop a running AWS IoT Greengrass Docker container, run `docker stop` or `docker-compose -f docker-compose.yml stop`. This action sends `SIGTERM` to the Greengrass process and shuts down all associated processes that were started in the container. The Docker container is initialized with the `docker-init` executable as process PID 1, which helps in removing any leftover zombie processes. For more information, see the [Specify an init process](https://docs.docker.com/engine/reference/run/#specify-an-init-process) in the Docker documentation.

<a name="see-docker-troubleshooting"></a>For information about troubleshooting issues with running AWS IoT Greengrass in a Docker container, see [Troubleshooting AWS IoT Greengrass in a Docker container](docker-troubleshooting.md).

# Troubleshooting AWS IoT Greengrass in a Docker container
<a name="docker-troubleshooting"></a>

Use the following information to help you troubleshoot issues with running AWS IoT Greengrass in a Docker container and to debug issues with AWS IoT Greengrass in the Docker container.

**Topics**
+ [Troubleshooting issues with running the Docker container](#troubleshooting-container-errors)
+ [Debugging AWS IoT Greengrass in a Docker container](#debugging-greengrass-in-docker)

## Troubleshooting issues with running the Docker container
<a name="troubleshooting-container-errors"></a>

Use the following information to help troubleshoot issues with running AWS IoT Greengrass in a Docker container.

**Topics**
+ [Error: Cannot perform an interactive login from a non TTY device](#docker-troubleshootin-ecr-get-login-password)
+ [Error: Unknown options: -no-include-email](#docker-troubleshooting-cli-version)
+ [Error: A firewall is blocking file Sharing between windows and the containers.](#docker-troubleshooting-firewall)
+ [Error: An error occurred (AccessDeniedException) when calling the GetAuthorizationToken operation: User: arn:aws:iam::*account-id*:user/<user-name> is not authorized to perform: ecr:GetAuthorizationToken on resource: \$1](#docker-troubleshooting-ecr-perms)
+ [Error: You have reached your pull rate limit](#docker-troubleshooting-too-many-requests)

### Error: Cannot perform an interactive login from a non TTY device
<a name="docker-troubleshootin-ecr-get-login-password"></a>

This error can occur when you run the `aws ecr get-login-password` command. Make sure that you installed the latest AWS CLI version 2 or version 1. We recommend that you use the AWS CLI version 2. For more information, see [Installing the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) in the *AWS Command Line Interface User Guide*.

### Error: Unknown options: -no-include-email
<a name="docker-troubleshooting-cli-version"></a>

This error can occur when you run the `aws ecr get-login` command. Make sure that you have the latest AWS CLI version installed (for example, Run: `pip install awscli --upgrade --user`). For more information, see [Installing the AWS Command Line Interface on Microsoft Windows](https://docs.aws.amazon.com/cli/latest/userguide/awscli-install-windows.html) in the *AWS Command Line Interface User Guide*.

### Error: A firewall is blocking file Sharing between windows and the containers.
<a name="docker-troubleshooting-firewall"></a>

You might receive this error or a `Firewall Detected` message when running Docker on a Windows computer. This can also occur if you are signed in on a virtual private network (VPN) and your network settings are preventing the shared drive from being mounted. In that situation, turn off VPN and re-run the Docker container.

### Error: An error occurred (AccessDeniedException) when calling the GetAuthorizationToken operation: User: arn:aws:iam::*account-id*:user/<user-name> is not authorized to perform: ecr:GetAuthorizationToken on resource: \$1
<a name="docker-troubleshooting-ecr-perms"></a>

You might receive this error when running the `aws ecr get-login-password` command if you don't have sufficient permissions to access an Amazon ECR repository. For more information, see [Amazon ECR Repository Policy Examples](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-policy-examples.html) and [Accessing One Amazon ECR Repository](https://docs.aws.amazon.com/AmazonECR/latest/userguide/security_iam_id-based-policy-examples.html) in the *Amazon ECR User Guide*.

### Error: You have reached your pull rate limit
<a name="docker-troubleshooting-too-many-requests"></a>

Docker Hub limits the number of pull requests that anonymous and Free Docker Hub users can make. If you exceed the rate limits for anonymous or free user pull requests, then you receive one of the following errors: 

  

```
ERROR: toomanyrequests: Too Many Requests.
```

  

```
You have reached your pull rate limit.
```

To resolve these errors, you can wait for a few hours before you try another pull request. If you plan on consistently submitting a large number of pull requests, see the [Docker Hub website](https://www.docker.com/increase-rate-limits) for information about rate limits, and options for authenticating and upgrading your Docker account. 

## Debugging AWS IoT Greengrass in a Docker container
<a name="debugging-greengrass-in-docker"></a>

To debug issues with a Docker container, you can persist the Greengrass runtime logs or attach an interactive shell to the Docker container.

### Persist Greengrass logs outside of the Docker container
<a name="debugging-docker-persist-logs"></a>

After you stop a AWS IoT Greengrass container, you can use the following `docker cp ` command to copy the Greengrass logs from the Docker container to a temporary logs directory. 

```
docker cp container-id:/greengrass/v2/logs /tmp/logs
```

To persist logs even after a container exits or is removed, you must run the AWS IoT Greengrass Docker container after bind-mounting the `/greengrass/v2/logs` directory. 

To bind-mount the `/greengrass/v2/logs` directory, do one of the following when you run a new AWS IoT Greengrass Docker container.
+ Include `-v /tmp/logs:/greengrass/v2/logs:ro` in your `docker run` command.

  Modify the `volumes` block in the Compose file to include the following line before you run your `docker-compose up` command.

  ```
  volumes:
   - /tmp/logs:/greengrass/v2/logs:ro
  ```

You can then check your logs at `/tmp/logs` on your host to see Greengrass logs while AWS IoT Greengrass is running inside the Docker container.

For information about running Greengrass Docker containers, see [Run AWS IoT Greengrass in Docker with manual provisioning](run-greengrass-docker-manual-provisioning.md) and [Run AWS IoT Greengrass in Docker with automatic provisioning](run-greengrass-docker-automatic-provisioning.md)

### Attach an interactive shell to the Docker container
<a name="debugging-docker-attach-shell"></a>

When you use `docker exec` to run commands inside the Docker container, those commands are not captured in the Docker logs. Logging your commands in the Docker logs can help you investigate the state of the Greengrass Docker container. Do one of the following:
+ Run the following command in a separate terminal to attach your terminal's standard input, output, and error to the running container. This enables you to view and control the Docker container from your current terminal.

  ```
  docker attach container-id
  ```
+ Run the following command in a separate terminal. This enables you to run your commands in interactive mode, even if the container is not attached.

  ```
  docker exec -it container-id sh -c "command > /proc/1/fd/1"
  ```

For general AWS IoT Greengrass troubleshooting, see [Troubleshooting AWS IoT Greengrass V2](troubleshooting.md).