amazon-web-servicesdockerdockerfileamazon-ecsecs-taskdefinition

Environment variable inside ecs container definition vs same environment variable defined in Dockerfile. Which one will be used?


If there is an environment variable SAMPLE_VALUE defined in the ecs task definition like so

{
  "containerDefinitions": [
    {
      "command": [
        "./app"
      ],
      "image": "sample-image:latest",
      "name": "sample-app",
      "environment": [
        {
          "name": "SAMPLE_VALUE",
          "value": "ABC"
        }
      ]
    }
  ]
}

If the same environment variable SAMPLE_VALUE is defined again inside the Dockerfile of sample-image like so

...
...
ENTRYPOINT ["run.sh", "app"]

The content of run.sh is

#!/bin/sh

export SAMPLE_VALUE=XYZ
exec $1

What value would app get from the variable SAMPLE_VALUE? Would it be XYZ or ABC?


Solution

  • The priority here would be:

    1. ENV declarations in the Dockerfile will be used by default.
    2. Environment-variable settings when you launch the container, including the ECS setting you show (but also docker run -e, Compose environment:, Kubernetes env:) override the image's ENV.
    3. Any environment variables the main container process sets itself will override both of these.

    So in your example, the main container process is run.sh, and that ignores whatever was previously in the environment and sets $SAMPLE_VALUE itself; when it exec the actual command, it will see SAMPLE_VALUE=xyz.

    You can illustrate this a little further by printing out the previous value:

    #!/bin/sh
    
    echo "SAMPLE_VALUE was ${SAMPLE_VALUE}"
    export SAMPLE_VALUE=xyz
    exec "$@"
    

    This will print out the ABC value set in the ECS definition, but then run the actual program with the value set to xyz.