7
votes

If I am running my docker based container in AWS ECS (EC2 Container Service), is there a way I can identify from inside the application whether my container is running on AWS ECS or not? This is required, because my docker container can run on any platform, but when it is running on AWS ECS, I need to perform some extra operations.

3

3 Answers

6
votes

Maybe you can use the Amazon ECS Container Agent Introspection:

The Amazon ECS container agent provides an API for gathering details about the container instance that the agent is running on and the associated tasks that are running on that instance.

You can use the curl command from within the container instance to query the Amazon ECS container agent (port 51678) and return container instance metadata or task information.

For instance, from within your container:

[ec2-user ~]$ curl http://localhost:51678/v1/metadata

Output:

{
  "Cluster": "default",
  "ContainerInstanceArn": "<container_instance_ARN>",
  "Version": "Amazon ECS Agent - v1.14.1 (467c3d7)"
}

Another criteria, as mention by the OP in the comments, is the Instance MetaData and User Data

Instance metadata is data about your instance that you can use to configure or manage the running instance. Instance metadata is divided into categories.

To view all categories of instance metadata from within a running instance, use the following URI:

http://169.254.169.254/latest/meta-data/

Note that you are not billed for HTTP requests used to retrieve instance metadata and user data.

You can use a tool such as cURL, or if your instance supports it, the GET command; for example:

[ec2-user ~]$ curl http://169.254.169.254/latest/meta-data/

So a successful curl is enough:

 curl -sL -w "%{http_code}\\n" "http://169.254.169.254/latest/meta-data/" -o /dev/null

That will display 200 if OK.
See "Linux script with curl to check webservice is up"

2
votes

After a lot of trial and error, I found the following most helpful:
Invoke http://169.254.169.254/latest/meta-data/
If you get 200 OK, then you can assume you are running inside AWS EC2/ECS.
But if you don't get 200 OK, then you are not running in AWS EC2/ECS.

0
votes

I've tried other alternatives that were posted before this response, but all of them did not work for ECS. I don't know if it has changed but now, if you want to verify if the container is running on ECS, you should call: http://169.254.170.2/v2/metadata/

More info: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-metadata-endpoint-v2.html

And if you want to verify if the container is running on EC2, you should call: http://169.254.169.254/latest/meta-data/

More info: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html