1. # Kubernetes CNI Calico GuideLine
  2. # 时间:20210820-[20:00-22:00]
  3. # 主题:Calico IPAM
  4. # 文档:https://www.yuque.com/docs/share/316fe6ba-25c9-4488-8beb-06eec2579b30?# 《20210820-Calico IPAM》
  5. # 作业:Calico IPAM
  1. # FAQ:

Calico IPAM

  1. Concepts
  2. IPAM in Kubernetes
  3. Kubernetes uses IPAM plugins to allocate and manage IP addresses assigned to pods. Different IPAM plugins provide different feature sets. Calico provides its own IPAM plugin called calico-ipam which is designed to work well with Calico and includes a number of features.
  4. Calico IPAM
  5. The calico-ipam plugin uses Calico’s IP pool resource to control how IP addresses are allocated to pods within the cluster. This is the default plugin used by most Calico installations.
  6. By default, Calico uses a single IP pool for the entire Kubernetes pod CIDR, but you can divide the pod CIDR into several pools. You can assign separate IP pools to particular selections of nodes, or to teams, users, or applications within a cluster using namespaces.
  7. You can control which pools Calico uses for each pod using
  8. node selectors
  9. an annotation on the pod’s namespace, or
  10. an annotation on the pod
  11. Calico also supports the host-local IPAM plugin. However, when using the host-local IPAM plugin some Calico features are not available.
  12. Calico IPAM blocks
  13. In Calico IPAM, IP pools are subdivided into blocks – smaller chunks that are associated with a particular node in the cluster. Each node in the cluster can have one or more blocks associated with it. Calico will automatically create and destroy blocks as needed as the number of nodes and pods in the cluster grows or shrinks.
  14. Blocks allow Calico to efficiently aggregate addresses assigned to pods on the same node, reducing the size of the routing table. By default Calico will try to allocate IP addresses from within an associated block, creating a new block if necessary. Calico can also assign addresses to pods on a node that are not within a block associated with that node. This allows for IP allocations independent of the node on which a pod is launched.
  15. By default, Calico creates blocks with room for 64 addresses (a /26), but you can control block sizes for each IP pool.
  16. Host-local IPAM
  17. The host-local plugin is a simple IP address management plugin. It uses predetermined CIDRs statically allocated to each node in order to choose addresses for pods. Once set, the CIDR for a node cannot be modified. Pods can be assigned addresses only from within the CIDR allocated to the node.
  18. Calico can use the host-local IPAM plugin, using the Node.Spec.PodCIDR field in the Kubernetes API to determine the CIDR to use for each node. However, per-node, per-pod, and per-namespace IP allocation features are not available using the host-local plugin.
  19. # https://github.com/projectcalico/libcalico-go/blob/release-v3.9/lib/ipam/ipam.go
  20. //
  21. 这里参考Calico 3.9版本代码,其中,CNI插件的流程就省去了,实际在CNI的ipam插件中会调用libcalico-go的相关代码,主要代码在lib/ipam/ipam.go,由于我们线上是默认的配置,也就是不会定义特殊的IP分配策略,因此主要逻辑集中在AutoAssign(ctx context.Context, args AutoAssignArgs)这个接口,而具体实现在autoAssign函数中:
  22. //
  23. func (c ipamClient) autoAssign(ctx context.Context, num int, handleID *string, attrs map[string]string, requestedPools []net.IPNet, version int, host string, maxNumBlocks int) ([]net.IPNet, error) {
  24. ...
  25. // 根据当前的节点获取可用的所有IP池
  26. pools, allPools, err := c.determinePools(requestedPools, version, *v3n)
  27. if err != nil {
  28. return nil, err
  29. }
  30. // 没有可用的池子就直接返回了
  31. if len(pools) == 0 {
  32. return nil, fmt.Errorf("no configured Calico pools for node %v", host)
  33. }
  34. ...
  35. ips := []net.IPNet{}
  36. newIPs := []net.IPNet{}
  37. // Record how many blocks we own so we can check against the limit later.
  38. numBlocksOwned := len(affBlocks)
  39. for len(ips) < num {
  40. // 所有的可用Block已经尝试完了
  41. if len(affBlocks) == 0 {
  42. logCtx.Infof("Ran out of existing affine blocks for host")
  43. break
  44. }
  45. // 选取当前Block列表第一个Block作为当前Block
  46. cidr := affBlocks[0]
  47. // 把第一个Block去除
  48. affBlocks = affBlocks[1:]
  49. for i := 0; i < datastoreRetries; i++ {
  50. ...
  51. // 尝试从当前的Block里分配一个可用的IP
  52. newIPs, err = c.assignFromExistingBlock(ctx, b, num, handleID, attrs, host, true)
  53. if err != nil {
  54. if _, ok := err.(cerrors.ErrorResourceUpdateConflict); ok {
  55. logCtx.WithError(err).Debug("CAS error assigning from affine block - retry")
  56. continue
  57. }
  58. logCtx.WithError(err).Warn("Couldn't assign from affine block, try next one")
  59. break
  60. }
  61. // 成功则添加到IP列表
  62. ips = append(ips, newIPs...)
  63. break
  64. }
  65. logCtx.Infof("Block '%s' provided addresses: %v", cidr.String(), newIPs)
  66. }
  67. // 获取 Calico IPAM 的配置
  68. // Calico IPAM 有两个全局配置项目(二者之中只能有一个为 true):
  69. // StrictAffinity: 严格的一个 host 对应一个地址块,如果地址块耗尽不再分配新的地址
  70. // AutoAllocateBlocks: 自动分配地址块,如果基于 host affine 的地址块耗尽,将分配新的地址块
  71. // 这部分配置没有对外暴露,只能通过人工配置对应 etcd key 值或者编程调用相关接口来进行配置
  72. // 相关讨论可参考 issue: https://github.com/projectcalico/calico/issues/1577
  73. // 直接设置 etcd key:/calico/ipam/v2/config/ => "{\"strict_affinity\":true}"
  74. config, err := c.GetIPAMConfig(ctx)
  75. if err != nil {
  76. return ips, err
  77. }
  78. // 如果自动分配Block选项打开并且当前IP还不够
  79. if config.AutoAllocateBlocks == true {
  80. rem := num - len(ips)
  81. retries := datastoreRetries
  82. for rem > 0 && retries > 0 {
  83. ...
  84. // 先看看还有没有没有被绑定到节点的Block
  85. subnet, err := c.blockReaderWriter.findUnclaimedBlock(ctx, host, version, pools, *config)
  86. if err != nil {
  87. if _, ok := err.(noFreeBlocksError); ok {
  88. // 没有就中断了
  89. logCtx.Info("No free blocks available for allocation")
  90. break
  91. }
  92. log.WithError(err).Error("Failed to find an unclaimed block")
  93. return ips, err
  94. }
  95. logCtx := log.WithFields(log.Fields{"host": host, "subnet": subnet})
  96. logCtx.Info("Found unclaimed block")
  97. for i := 0; i < datastoreRetries; i++ {
  98. // 有的话,就绑定到当前节点
  99. pa, err := c.blockReaderWriter.getPendingAffinity(ctx, host, *subnet)
  100. if err != nil {
  101. if _, ok := err.(cerrors.ErrorResourceUpdateConflict); ok {
  102. logCtx.WithError(err).Debug("CAS error claiming pending affinity, retry")
  103. continue
  104. }
  105. logCtx.WithError(err).Errorf("Error claiming pending affinity")
  106. return ips, err
  107. }
  108. // 新绑定了Block,尝试在新Block里分配IP
  109. b, err := c.getBlockFromAffinity(ctx, pa)
  110. ...
  111. newIPs, err := c.assignFromExistingBlock(ctx, b, rem, handleID, attrs, host, config.StrictAffinity)
  112. ...
  113. // 分配成功
  114. ips = append(ips, newIPs...)
  115. rem = num - len(ips)
  116. break
  117. }
  118. }
  119. if retries == 0 {
  120. return ips, errors.New("Max retries hit - excessive concurrent IPAM requests")
  121. }
  122. }
  123. // 如果IP分配还不够(也就是说已绑定的Block里的IP都分完了,并且也没有没有可绑定的新IPBlock了)并且IP还没分完,
  124. // 并且StrictAffinity为false
  125. rem := num - len(ips)
  126. if config.StrictAffinity != true && rem != 0 {
  127. logCtx.Infof("Attempting to assign %d more addresses from non-affine blocks", rem)
  128. // Iterate over pools and assign addresses until we either run out of pools,
  129. // or the request has been satisfied.
  130. logCtx.Info("Looking for blocks with free IP addresses")
  131. for _, p := range pools {
  132. // 在所有的Pool里,随机选一个Block,在这个Block里找可用的IP地址
  133. newBlock := randomBlockGenerator(p, host)
  134. for rem > 0 {
  135. // Grab a new random block.
  136. blockCIDR := newBlock()
  137. if blockCIDR == nil {
  138. logCtx.Warningf("All addresses exhausted in pool %s", p.Spec.CIDR)
  139. break
  140. }
  141. for i := 0; i < datastoreRetries; i++ {
  142. b, err := c.blockReaderWriter.queryBlock(ctx, *blockCIDR, "")
  143. ...
  144. newIPs, err := c.assignFromExistingBlock(ctx, b, rem, handleID, attrs, host, false)
  145. ...
  146. // 分配成功
  147. ips = append(ips, newIPs...)
  148. rem = num - len(ips)
  149. break
  150. }
  151. }
  152. }
  153. }
  154. // 最后,如果执行到这里,意味着根据配置,无法再分配IP或者干脆全局都没有IP可用了
  155. logCtx.Infof("Auto-assigned %d out of %d IPv%ds: %v", len(ips), num, version, ips)
  156. return ips, nil
  157. }
  1. 从上面的代码可以看到,Calico分配IP的逻辑为:
  2. 如果节点有已绑定的IP Block,则从这些IP Block中分配IP
  3. 如果第1步失败(没有已绑定的IP Block,或者这些绑定的Block里IP耗尽),判断AutoAllocateBlocks为true,则寻找一个没有被绑定的IP Block,并绑定到当前节点,再执行分配逻辑
  4. 如果第2步失败(AutoAllocateBlocks为false或者没有空闲的IP Block),判断StrictAffinity为false,则从所有IP Blocks中寻找未使用的IP
  5. 经历前1-3步依然没有分配好IP,则失败
  6. 阅读了上面的代码,则可以知道在默认配置(StrictAffinity: true, AutoAllocateBlocks: false)下,当节点已有IP Block中没有空闲IP并且也没有空闲IP Block时,就会发生之前所说的情况,而恰好Calico在利用BIRD进行BGP路由广播时,针对每个已绑定的IP Block会设置blackhole路由,从而会导致Pod IP无法访问的问题。
  7. 根据上面的情况,目前看我们当前使用Calico还是有些问题的,特别是对当前IPPool的处理上。
  8. 一方面也是Calico的实现并不是特别好,比如这个Issue(https://github.com/projectcalico/calico/issues/2713)里提到的,当前针对节点的IP Block绑定,只有自动绑定的功能,但是没有自动解绑定的功能,解绑只有在删除Calico Node对象的时候才会发生,这会引发一个问题,就是说如果集群中节点有变化了,比如某台机器下线,并有新的节点上线做替换。那如果不手动操作Calico删除对应Node,就会导致之前的IP Block不被释放,也就一直无法没绑定到其他节点。
  9. 另一方面也是我们的使用问题,没有及时跟进Calico的更新,线上版本相对版本旧一点,导致在分配Block的时候,只能固定以/26的BlockSize,也就是说一个IPBlock包含64个IP,而目前每台节点的Pod数量限制是默认的110,那么在使用2个Block也就是128个IP的时候就会出现比较大的浪费现象。这个问题在Allow the blockSize to be configured for Calico IPAM(https://github.com/projectcalico/libcalico-go/pull/931)中已经得到改进,目标版本v3.3.0。
  10. 因此,在高于v3.3.0版本的Calico中可以自定义BlockSize,比如定义为30,也就是一个Block 4个IP,这样可以比较好的提升IP的利用率,当然这样带来的问题是对外广播的路由数量的增加,所以需要权衡,找到一个合适的BlockSize。

Assign IP Addresses Based On Topology

  1. # Assign blocks of IP addresses from an IP pool for different topological areas.
  2. If you have workloads in different regions, zones, or rack, you may want them to get IP addresses from the same IP pool. This strategy is useful for reducing the number of routes that are required in the network, or to meet requirements imposed by an external firewall device or policy. Calico makes it easy to do this using an IP pool resource with node labels and node selectors.
  3. # Concepts
  4. # IP address assignment
  5. Topology-based IP address assignment requires addresses to be per-host (node). As such, Kubernetes annotations cannot be used because annotations are only per-namespace and per-pod. And although you can configure IP addresses for nodes in the CNI configuration, you are making changes within the host’s file system. The best option is to use node-selection IP address assignment using IP pools.
  6. # Node-selection IP address management
  7. Node selection-based IP address assignment is exactly what it sounds like: node labels are set, and Calico uses node selectors to decide which IP pools to use when assigning IP addresses to the node.
  8. # Best practice
  9. Nodes only assign workload addresses from IP pools which select them. To avoid having a workload not get an IP and fail to start, it is important to ensure that all nodes are selected by at least one IP pool.
  10. # Tutorial
  11. In this tutorial, we create a cluster with four nodes across two racks (two nodes/rack).
  12. -------------------
  13. | router |
  14. -------------------
  15. | |
  16. --------------- ---------------
  17. | rack-0 | | rack-1 |
  18. --------------- ---------------
  19. | kube-node-0 | | kube-node-2 |
  20. - - - - - - - - - - - - - - - -
  21. | kube-node-1 | | kube-node-3 |
  22. - - - - - - - - - - - - - - - -
  23. Using the pod IP range 192.168.0.0/16, we target the following setup: reserve the 192.168.0.0/24 and 192.168.1.0/24 pools for rack-0, rack-1. Let’s get started.
  24. By installing Calico without setting the default IP pool to match, running calicoctl get ippool -o wide shows that Calico created its default IP pool of 192.168.0.0/16:
  25. NAME CIDR NAT IPIPMODE DISABLED SELECTOR
  26. default-ipv4-ippool 192.168.0.0/16 true Always false all()
  27. #1.Delete the default IP pool.
  28. Since the default-ipv4-ippool IP pool resource already exists and accounts for the entire /16 block, we will have to delete this first:
  29. calicoctl delete ippools default-ipv4-ippool
  30. #2.Label the nodes.
  31. To assign IP pools to specific nodes, these nodes must be labelled using kubectl label.
  32. kubectl label nodes kube-node-0 rack=0
  33. kubectl label nodes kube-node-1 rack=0
  34. kubectl label nodes kube-node-2 rack=1
  35. kubectl label nodes kube-node-3 rack=1
  36. #3.Create an IP pool for each rack.
  37. calicoctl create -f -<<EOF
  38. apiVersion: projectcalico.org/v3
  39. kind: IPPool
  40. metadata:
  41. name: rack-0-ippool
  42. spec:
  43. cidr: 192.168.0.0/24
  44. ipipMode: Always
  45. natOutgoing: true
  46. nodeSelector: rack == "0"
  47. EOF
  48. calicoctl create -f -<<EOF
  49. apiVersion: projectcalico.org/v3
  50. kind: IPPool
  51. metadata:
  52. name: rack-1-ippool
  53. spec:
  54. cidr: 192.168.1.0/24
  55. ipipMode: Always
  56. natOutgoing: true
  57. nodeSelector: rack == "1"
  58. EOF
  59. We should now have two enabled IP pools, which we can see when running calicoctl get ippool -o wide:
  60. NAME CIDR NAT IPIPMODE DISABLED SELECTOR
  61. rack-0-ippool 192.168.0.0/24 true Always false rack == "0"
  62. rack-1-ippool 192.168.1.0/24 true Always false rack == "1"
  63. #4.Verify that the IP pool node selectors are being respected.
  64. We will create an nginx deployment with five replicas to get a workload running on each node.
  65. kubectl run nginx --image nginx --replicas 5
  66. Check that the new workloads now have an address in the proper IP pool allocated for the rack that the node is on with kubectl get pods -owide.
  67. NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
  68. nginx-5c7588df-prx4z 1/1 Running 0 6m3s 192.168.0.64 kube-node-0 <none> <none>
  69. nginx-5c7588df-s7qw6 1/1 Running 0 6m7s 192.168.0.129 kube-node-1 <none> <none>
  70. nginx-5c7588df-w7r7g 1/1 Running 0 6m3s 192.168.1.65 kube-node-2 <none> <none>
  71. nginx-5c7588df-62lnf 1/1 Running 0 6m3s 192.168.1.1 kube-node-3 <none> <none>
  72. nginx-5c7588df-pnsvv 1/1 Running 0 6m3s 192.168.1.64 kube-node-2 <none> <none>
  73. The grouping of IP addresses assigned to the workloads differ based on what node that they were scheduled to. Additionally, the assigned address for each workload falls within the respective IP pool that selects the rack that they run on.

Use a specific IP address with a pod

  1. # Before you begin…
  2. # Verify that you are using Calico IPAM.
  3. To verify, ssh to one of your Kubernetes nodes and view the CNI configuration.
  4. cat /etc/cni/net.d/10-calico.conflist
  5. Look for the “type” entry:
  6. "ipam": {
  7. "type": "calico-ipam"
  8. },
  9. #
  10. # 给pod指定一个特定的ip地址:
  11. #1.创建新的ippool:
  12. [root@ovs ~]# cat net.yaml
  13. apiVersion: projectcalico.org/v3
  14. kind: IPPool
  15. metadata:
  16. name: external-pool
  17. spec:
  18. cidr: 172.16.0.0/26
  19. blockSize: 29
  20. ipipMode: Always
  21. natOutgoing: true
  22. #2.指定IP地址:
  23. [root@ovs ~]# cat calico_static.yaml
  24. apiVersion: v1
  25. kind: Pod
  26. metadata:
  27. name: calico-static-pod
  28. labels:
  29. app: myapp
  30. annotations:
  31. cni.projectcalico.org/ipAddrs: "[\"172.16.0.2\"]"
  32. spec:
  33. containers:
  34. - name: static-container
  35. image: burlyluo/nettoolbox
  36. [root@ovs ~]#
  37. # show output:
  38. [root@k8s-1 ~]# calicoctl get ippool -o wide
  39. NAME CIDR NAT IPIPMODE VXLANMODE DISABLED SELECTOR
  40. default-ipv4-ippool 10.244.0.0/16 true Always Never false all()
  41. external-pool 172.16.0.0/26 true Always Never false all()
  42. [root@k8s-1 ~]#
  43. # 地址信息:
  44. [root@k8s-1 ~]# kubectl get pods -o wide
  45. NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
  46. calico-static-pod 1/1 Running 0 4m22s 172.16.0.2 k8s-2 <none> <none>
  47. [root@k8s-1 ~]#
  48. # Deploy DEMO:
  49. apiVersion: apps/v1
  50. kind: Deployment
  51. metadata:
  52. name: static-ip
  53. spec:
  54. selector:
  55. matchLabels:
  56. app: nginx
  57. replicas: 1 # tells deployment to run 1 pods matching the template
  58. template:
  59. metadata:
  60. labels:
  61. app: nginx
  62. annotations:
  63. "cni.projectcalico.org/ipAddrs": "[\"172.16.0.5\"]"
  64. spec:
  65. containers:
  66. - name: nginx
  67. image: burlyluo/nettoolbox
  68. #
  69. # Note the use of the escaped \" for the inner double quotes around the addresses.
  70. # The address must be within a configured Calico IP pool and not currently in use. The annotation must be present when the pod is created; adding it later has no effect.
  71. # Note that currently only a single IP address is supported per-pod using this annotation

Migrate from one IP pool to another

  1. # Step 1: Add a new IP pool
  2. We add a new IPPool with the CIDR range, 10.0.0.0/16.
  3. apiVersion: projectcalico.org/v3
  4. kind: IPPool
  5. metadata:
  6. name: new-pool
  7. spec:
  8. cidr: 10.0.0.0/16
  9. ipipMode: Always
  10. natOutgoing: true
  11. # 查看系统上的ippool信息:
  12. [root@k8s-1 ~]# calicoctl get ippool -o wide
  13. NAME CIDR NAT IPIPMODE VXLANMODE DISABLED SELECTOR
  14. default-ipv4-ippool 10.244.0.0/16 true Always Never false all()
  15. external-pool 172.16.0.0/26 true Always Never false all()
  16. new-pool 10.0.0.0/16 true Always Never false all()
  17. [root@k8s-1 ~]#
  18. # 2.Disable the old IP pool:
  19. calicoctl get ippool -o yaml > pool.yaml
  20. Disable this IP pool by setting: disabled: true
  21. [root@k8s-1 ~]# cat pool.yaml
  22. apiVersion: projectcalico.org/v3
  23. items:
  24. - apiVersion: projectcalico.org/v3
  25. kind: IPPool
  26. metadata:
  27. creationTimestamp: "2021-04-04T04:55:21Z"
  28. name: default-ipv4-ippool
  29. resourceVersion: "127281"
  30. uid: ce563f34-8423-4b39-9653-d98cd77bad8a
  31. spec:
  32. blockSize: 26
  33. cidr: 10.244.0.0/16
  34. disabled: true
  35. ipipMode: Always
  36. natOutgoing: true
  37. nodeSelector: all()
  38. vxlanMode: Never
  39. disabled: true # disable this ippool
  40. - apiVersion: projectcalico.org/v3
  41. kind: IPPool
  42. metadata:
  43. creationTimestamp: "2021-08-19T03:05:39Z"
  44. name: external-pool
  45. resourceVersion: "127282"
  46. uid: 9a8de79a-90af-4a46-a4b7-0649ba5b2453
  47. spec:
  48. blockSize: 29
  49. cidr: 172.16.0.0/26
  50. ipipMode: Always
  51. natOutgoing: true
  52. nodeSelector: all()
  53. vxlanMode: Never
  54. disabled: true # disable this ippool
  55. - apiVersion: projectcalico.org/v3
  56. kind: IPPool
  57. metadata:
  58. creationTimestamp: "2021-08-20T04:53:15Z"
  59. name: new-pool
  60. resourceVersion: "127286"
  61. uid: adddcb37-e7c9-4db4-b25b-d78795f9619f
  62. spec:
  63. blockSize: 26
  64. cidr: 10.0.0.0/16
  65. ipipMode: Always
  66. natOutgoing: true
  67. nodeSelector: all()
  68. vxlanMode: Never
  69. kind: IPPoolList
  70. metadata:
  71. resourceVersion: "127644"
  72. #3.Step 3: Delete pods from the old IP pool
  73. [root@ovs ~]# kubectl get pods -o wide -w
  74. NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
  75. cni-cgchc 1/1 Terminating 0 3m38s 172.16.0.17 k8s-1 <none> <none>
  76. cni-mm9pd 1/1 Terminating 1 137d 10.244.200.194 k8s-2 <none> <none>
  77. myapp-pod 1/1 Running 1 90m 172.16.0.2 k8s-2 <none> <none>
  78. static-ip-5b7f96bbfd-sztpq 1/1 Running 0 76m 172.16.0.5 k8s-2 <none> <none>
  79. cni-cgchc 1/1 Terminating 0 3m50s 172.16.0.17 k8s-1 <none> <none>
  80. cni-mm9pd 1/1 Terminating 1 137d 10.244.200.194 k8s-2 <none> <none>
  81. cni-cgchc 0/1 Terminating 0 3m51s <none> k8s-1 <none> <none>
  82. cni-mm9pd 0/1 Terminating 1 137d <none> k8s-2 <none> <none>
  83. cni-cgchc 0/1 Terminating 0 3m52s <none> k8s-1 <none> <none>
  84. cni-cgchc 0/1 Terminating 0 3m52s <none> k8s-1 <none> <none>
  85. cni-wpg5g 0/1 Pending 0 0s <none> <none> <none> <none>
  86. cni-wpg5g 0/1 Pending 0 0s <none> k8s-1 <none> <none>
  87. cni-wpg5g 0/1 ContainerCreating 0 0s <none> k8s-1 <none> <none>
  88. cni-wpg5g 0/1 ContainerCreating 0 1s <none> k8s-1 <none> <none>
  89. cni-mm9pd 0/1 Terminating 1 137d <none> k8s-2 <none> <none>
  90. cni-mm9pd 0/1 Terminating 1 137d <none> k8s-2 <none> <none>
  91. cni-zc2jl 0/1 Pending 0 0s <none> <none> <none> <none>
  92. cni-zc2jl 0/1 Pending 0 0s <none> k8s-2 <none> <none>
  93. cni-zc2jl 0/1 ContainerCreating 0 0s <none> k8s-2 <none> <none>
  94. cni-zc2jl 0/1 ContainerCreating 0 0s <none> k8s-2 <none> <none>
  95. cni-wpg5g 1/1 Running 0 16s 10.0.231.193 k8s-1 <none> <none>
  96. cni-zc2jl 1/1 Running 0 16s 10.0.200.193 k8s-2 <none> <none>
  97. # Step4:Delete the old ippool:
  98. calicoctl delete pool default-ipv4-ippool

Specific IPPOOL

  1. Concepts
  2. Kubernetes pod CIDR
  3. The Kubernetes pod CIDR is the range of IPs Kubernetes expects pod IPs to be assigned from. It is defined for the entire cluster and is used by various Kubernetes components to determine whether an IP belongs to a pod. For example, kube-proxy treats traffic differently if that traffic is from a pod than if it is not. All pod IPs must be in the CIDR range for Kubernetes to function correctly.
  4. IP Pool
  5. IP pools are ranges of IP addresses from which Calico assigns pod IPs. By default, Calico creates an IP pool for the entire Kubernetes pod CIDR, but you can change this to break the pod CIDR up into several pools. You can control which pool Calico uses for each pod using node selectors, or annotations on the pod or the pod’s namespace.
  6. Before you begin…
  7. The features in this How to guide require:
  8. Calico IPAM
  9. If you are not sure, ssh to one of your Kubernetes nodes and examine the CNI configuration.
  10. cat /etc/cni/net.d/10-calico.conflist
  11. Look for the entry:
  12. "ipam": {
  13. "type": "calico-ipam"
  14. },
  15. If it is present, you are using the Calico IPAM. If the IPAM is not Calico, or the 10-calico.conflist file does not exist, you cannot use these features in your cluster.
  16. Also, cluster administrators must have configured IP pools to define the valid IP ranges to use for allocating pod IP addresses.
  17. How to
  18. Restrict a pod to use an IP address range
  19. Annotate the pod with key cni.projectcalico.org/ipv4pools and/or cni.projectcalico.org/ipv6pools and value set to a list of IP pool names, enclosed in brackets. For example:
  20. cni.projectcalico.org/ipv4pools: '["pool-1", "pool-2"]'
  21. Note the use of the escaped " for the inner double quotes around the pool names.
  22. Restrict all pods within a namespace to use an IP address range
  23. Annotate the namespace with key cni.projectcalico.org/ipv4pools and/or cni.projectcalico.org/ipv6pools and value set to a list of IP pool names, enclosed in brackets. For example:
  24. cni.projectcalico.org/ipv4pools: '["pool-1", "pool-2"]'
  25. Note the use of the escaped \" for the inner double quotes around the pool names.
  26. If both the pod and the pod’s namespace have the annotation, the pod annotation takes precedence.
  27. The annotation must be present at the time the pod is created. Adding it to an existing pod has no effect.
  28. apiVersion: projectcalico.org/v3
  29. kind: IPPool
  30. metadata:
  31. name: new-pool-ns
  32. spec:
  33. cidr: 11.0.0.0/16
  34. ipipMode: Always
  35. natOutgoing: true
  36. ###############################################################################
  37. 多pod固定IP池
  38. 需要创建额外IP池(除了默认IP池)。利用注解cni.projectcalico.org/ipv4pools。
  39. 示例yaml配置如下
  40. [root@k8s-master3 ~]# cat ippool1.yaml
  41. apiVersion: projectcalico.org/v3
  42. kind: IPPool
  43. metadata:
  44. name: new-pool1
  45. spec:
  46. blockSize: 31
  47. cidr: 10.21.0.0/31
  48. ipipMode: Never
  49. natOutgoing: true
  50. [root@k8s-master3 ~]# calicoctl create -f ippool1.yaml
  51. Successfully created 1 'IPPool' resource(s)
  52. [root@k8s-master3 ~]# cat ippool2.yaml
  53. apiVersion: projectcalico.org/v3
  54. kind: IPPool
  55. metadata:
  56. name: new-pool2
  57. spec:
  58. blockSize: 31
  59. cidr: 10.21.0.2/31
  60. ipipMode: Never
  61. natOutgoing: true
  62. [root@k8s-master3 ~]# calicoctl create -f ippool2.yaml
  63. Successfully created 1 'IPPool' resource(s)
  64. [root@k8s-master3 ~]#
  65. [root@k8s-master3 ~]#
  66. [root@k8s-master3 ~]# calicoctl get ippool
  67. NAME CIDR SELECTOR
  68. default-ipv4-ippool 10.20.0.0/16 all()
  69. new-pool1 10.21.0.0/31 all()
  70. new-pool2 10.21.0.2/31 all()
  71. root@k8s-master3 ~]# cat nginx.yaml
  72. apiVersion: apps/v1 # for versions before 1.9.0 use apps/v1beta2
  73. kind: Deployment
  74. metadata:
  75. name: nginx-deployment
  76. spec:
  77. selector:
  78. matchLabels:
  79. app: nginx
  80. replicas: 4 # tells deployment to run 2 pods matching the template
  81. template:
  82. metadata:
  83. labels:
  84. app: nginx
  85. annotations:
  86. "cni.projectcalico.org/ipv4pools": "[\"new-pool1\",\"new-pool2\"]"
  87. spec:
  88. containers:
  89. - name: nginx
  90. image: nginx:1.7.9
  91. ports:
  92. - containerPort: 80
  93. [root@k8s-master3 ~]# kubectl create -f nginx.yaml
  94. deployment.apps/nginx-deployment created
  95. [root@k8s-master3 ~]# kubectl get pods -o wide
  96. NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
  97. nginx-deployment-f49447c5d-4k4px 1/1 Running 0 11s 10.21.0.0 k8s-master4 <none> <none>
  98. nginx-deployment-f49447c5d-5sbrx 1/1 Running 0 11s 10.21.0.2 k8s-master4 <none> <none>
  99. nginx-deployment-f49447c5d-flfb8 1/1 Running 0 11s 10.21.0.3 k8s-master4 <none> <none>
  100. nginx-deployment-f49447c5d-q4945 1/1 Running 0 11s 10.21.0.1 k8s-master4 <none> <none>
  101. # 指定namespace:
  102. kubectl get ns
  103. [root@k8s-1 ~]# kubectl edit ns cc
  104. # Please edit the object below. Lines beginning with a '#' will be ignored,
  105. # and an empty file will abort the edit. If an error occurs while saving this file will be
  106. # reopened with the relevant failures.
  107. #
  108. apiVersion: v1
  109. kind: Namespace
  110. metadata:
  111. annotations:
  112. cni.projectcalico.org/ipv4pools: '["new-pool-ns"]' ### Add this annotations
  113. creationTimestamp: "2021-08-20T05:20:44Z"
  114. name: cc
  115. resourceVersion: "130057"
  116. uid: bb8ed59d-04c8-4449-864b-ced54e64bb59
  117. spec:
  118. finalizers:
  119. - kubernetes
  120. status:
  121. phase: Active
  122. ~
  123. 创建pod:
  124. #kubectl run ccc --image=burlyluo/nettoolbox -ncc
  125. # ippool 信息:
  126. [root@k8s-1 ~]# calicoctl get ippool -o wide
  127. NAME CIDR NAT IPIPMODE VXLANMODE DISABLED SELECTOR
  128. default-ipv4-ippool 10.244.0.0/16 true Always Never true all()
  129. external-pool 172.16.0.0/26 true Always Never true all()
  130. new-pool 10.0.0.0/16 true Always Never false all()
  131. new-pool-ns 11.0.0.0/16 true Always Never false all()
  132. [root@k8s-1 ~]#
  133. [root@k8s-1 ~]# kubectl get pods -o wide -ncc
  134. NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
  135. ccc 1/1 Running 0 57m 11.0.200.193 k8s-2 <none> <none>
  136. [root@k8s-1 ~]#