Fargate是AWS的无服务器计算引擎。在EKS中使用Fargate,您无需管理服务器,它开箱即用,我们只需定义Pod所需的CPU和内存即可让pod在Fargate上运行起来。前面我们学习过# AWS EKS 计算资源自动扩缩之Cluster Autoscaler[AWS 中国宁夏区],当您选择EC2作为EKS的工作节点时,您需要自己创建和管理一个EC2节点组,这需要你承担更多管理责任,带来了运维负担。相比下Fargate简单,精确匹配了pod的资源需求,减少了资源浪费。
Fargate最大的优点在其开箱即用的免运维简单性,尽量按需匹配pod所需资源减少资源浪费从而提升了性价比(例如4C8G的EC2上运行了一个4C4G的Java程序就导致了EC2浪费了4G的内存),最后是其底层架构做了优化,pod弹性就绪的速度更快。
本文基于上一篇文章 AWS EKS 创建K8S集群[AWS 中国宁夏区]中创建的AWS EKS集群进行说明。
设置Fargate
AWS IAM Role设置
fargate正常运行需要有Amazon EKS Pod execution IAM role,详情可以参考Amazon EKS Pod execution IAM role
编辑policy内容,并保存为pod-execution-role-trust-policy.json
,其中region-code
和aws-account
需要填你真实的内容
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Condition": {
"ArnLike": {
"aws:SourceArn": "arn:aws-cn:eks:<region-code>:<aws-account>:fargateprofile/*"
}
},
"Principal": {
"Service": "eks-fargate-pods.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
创建role,名称可以自定义,我设置为AmazonEKSFargatePodExecutionRole
aws iam create-role --role-name AmazonEKSFargatePodExecutionRole --assume-role-policy-document file://"pod-execution-role-trust-policy.json"
将AmazonEKSFargatePodExecutionRole
和AmazonEKSFargatePodExecutionRolePolicy
关联
aws iam attach-role-policy --policy-arn arn:aws-cn:iam::aws:policy/AmazonEKSFargatePodExecutionRolePolicy --role-name AmazonEKSFargatePodExecutionRole
如果你习惯AWS控制台可视化操作,上述步骤也可以直接在AWS控制台完成,如下图是我创建好的role
创建fargate profile
填写自己的fargate profile名称,这里我简单的写成fargate-profile,并选定刚才创建的AmazonEKSFargatePodExecutionRole
为这个profie填入合适的namespace设置,详情见AWS Fargate profile
例如下面我设置的pod选择器规则为prod-*
,如果pod部署在以prod-
开头的namespace中,并且标签选择器为infrastructure=fargate
时,那么pod就优先运行在fargate上,而不是默认的EC2上。
检查上述设置后直接创建profile,创建需要几分钟
创建完成
测试fargate的使用
这里是一个简单的nginx deployment样例,请注意它的namesapce必须要和fargate proflie中的namespace设置相匹配,匹配规则为AWS Fargate profile
apiVersion: apps/v1
kind: Deployment
metadata:
name: eks-sample-linux-deployment
# 必须和fargate proflie中的namespace设置相匹配,https://docs.aws.amazon.com/eks/latest/userguide/fargate-profile.html
namespace: prod-fargate
labels:
app: eks-sample-linux-app
spec:
replicas: 3
selector:
matchLabels:
app: eks-sample-linux-app
template:
metadata:
labels:
app: eks-sample-linux-app
# 可选,必须和fargate proflie中的Match labels相匹配,https://docs.aws.amazon.com/eks/latest/userguide/fargate-profile.html
infrastructure: fargate
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/arch
operator: In
values:
- amd64
- arm64
containers:
- name: nginx
image: public.ecr.aws/nginx/nginx:1.23
ports:
- name: http
containerPort: 80
imagePullPolicy: IfNotPresent
nodeSelector:
kubernetes.io/os: linux
部署上面的deployment:
kubectl create ns prod-fargate
kubectl apply -f nginx-deployment.yml
等待片刻我们会发现fargate作为底层计算资源已经运行了正确的nginx
通过kubectl进行查询
通过aws控制台进行查询
fargate和ec2 node group不一样,fargate只需要你设置好pod的HPA后,pod就可以自动的水平扩展并及时获取对应的fargate计算资源,不再需要autosacler等插件。