AWS EC2 gai.conf

gai.conf is a configuration file in Linux systems that controls the behavior of the getaddrinfo library function. This function is used to translate hostnames or IP addresses into socket addresses that are usable by various network protocols. By configuring gai.conf, you can specify the priority and order in which different address families (such as IPv4 and IPv6) are returned by the getaddrinfo function.

The gai.conf file is located in the /etc directory and has a simple syntax. Each line in the file specifies a preference value for a specific address family or an address prefix. The higher the preference value, the more preferred the address family is.

For example, to prefer IPv4 over IPv6, you can add the following line to gai.conf:

1
precedence ::ffff:0:0/96  100

Yesterday I had an issue in deploying my codes on AWS EC2 instances, so when I investigate the CodeDeploy agent logs, I saw that it can not connect !! After checking different things, I noticed that my ECS subnet is private and just its IPv4 has route to NAT gateway. But my EC2 was trying to connect to CodeDeploy via IPv6 that was not routable.

So I added gai.conf as below in /etc and rebooted the EC2 instances and deployed the code without issue.

1
2
3
4
5
6
7
8
9
abel  ::/0          1
label  2002::/16     2
label ::/96          3
label ::ffff:0:0/96  4
precedence  ::1/128       50
precedence  ::/0          40
precedence  2002::/16     30
precedence ::/96          20
precedence ::ffff:0:0/96  100

The label lines are defining labels for various address prefixes. For example, label ::1/128 1 is defining a label for the loopback address (::1) with a label value of 1.

The precedence lines are setting the precedence values for the various address prefixes. The higher the precedence value, the more preferred the address family is. For example, precedence ::ffff:0:0/96 100 is giving IPv4 addresses a higher priority than any other address family, as the precedence value of 100 is the highest.

So, the priority and order of different address families for the getaddrinfo library function would be as follows:

IPv4 (::ffff:0:0/96) with a precedence value of 100

IPv6 with a prefix of 2002::/16 with a precedence value of 30

IPv6 with a prefix of ::/96 with a precedence value of 20

IPv6 with a prefix of ::/0 with a precedence value of 40

IPv6 loopback address (::1/128) with a precedence value of 50

This configuration is giving IPv4 addresses the highest priority, followed by the other address families in the order specified.

updatedupdated2023-08-222023-08-22