In order to run tasks as a non-root user, you must have the user at first. Start by creating the user and group in the Dockerfile with something like:
RUN groupadd -r <group name> && useradd --no-log-init -r -g <group name> <user name>"
Then, you can run application as a non-root user by using “USER ” in Dockerfile. Reference the Docker document for USER instruction, we can see:
- The USER instruction sets the user name (or UID) and optionally the user group (or GID) to use when running the image and for any RUN, CMD and ENTRYPOINT instructions that follow it in the Dockerfile. You can use the “USER” statement to mark that the docker container when run should be run as the “” user. For more information, you could reference [1][2].
In this way, you must build the docker image with a user and upload it to ECR before you run the ECS tasks.
If you do not use the "USER" instruction in Dockerfile, you can specify the "user" parameter with an username when creating the ECS task definition as an alternative way. To specify a "user" parameter in task definition will force to run your application as this user. Moreover, the user must exist in the docker image, otherwise the task will fail to start.
The format in ECS task definition for "user" parameter can be as following:
- user
- user:group
- uid
- uid:gid
- user:gid
- uid:group
And please notice that this parameter is not supported for Windows containers. For more details about "user" parameter, please refer to our public document [3].
For example, the following is the snippet of my task definition:
{
"containerDefinitions": [
{
.
.
"user": “<user name>”, ### The task will be run as <user name>.
"privileged": null,
.
.
}
],
.
}
Finally, please note that running as non-root user can bring its own challenges, e.g. if you start a process to LISTEN on 80, this is something a non-root user can't do.
Ref:
[1] User - Best practices for writing Dockerfiles
https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#user
[2] https://docs.docker.com/engine/reference/builder/#user
[3] Task Definition Parameters - Container Definitions - https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#container_definitions