I built this image and push it to my ECR repo
FROM ubuntu:latest
RUN useradd -ms /bin/bash toto_user
USER toto_user
Then, I added this user to my task definition, toto_user. The task is not running, even as a root user. If I SSH to that ec2 and run the following command, it is working:
docker run -v /:/host -it 09999999999.dkr.ecr.us-east-1.amazonaws.com/hello-world:avocado_secret_theft1
How to solve this, any ideas?
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:
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:
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