How to fix the IP address of a pod in k8s?

In Kubernetes, the IP address of a Pod is automatically assigned and managed by the Kubernetes system, and may change when the Pod is restarted or moved. However, if you need to fix the IP address of a Pod, you can use Kubernetes’ Headless Service and StatefulSet.

  1. To create a Headless Service: A Headless Service is a Service without a Cluster IP, it does not assign a stable virtual IP address for Pods, instead returning the IP addresses of each Pod through DNS. You can create a Headless Service using the following command:
  2. API version is v1.
    Service type is my-service with label app set to my-app.
    Cluster IP is set to None.
    Service selector is my-app.
    Port protocol is TCP, with port and targetPort set to 80 and 8080 respectively.
  3. Create a StatefulSet: A StatefulSet is a controller used to manage stateful applications, assigning a unique identifier to each Pod which helps to maintain stability during Pod restarts or migrations. To create a StatefulSet, use the following command:
  4. API version is set to apps/v1 and a StatefulSet named my-statefulset is created with 3 replicas, each running a container named my-container with image my-image and listening on port 8080. The service name is set to my-service.
  5. In the spec of StatefulSet, the serviceName field specifies the name of the Headless Service, allowing the StatefulSet to use the Headless Service to manage the network of its Pods.

By following the steps above, you can use Headless Service and StatefulSet to assign a fixed IP address to a Pod. Each Pod’s IP address will be resolved via DNS to the Pod name, and will remain stable even when the Pod is restarted or migrated.

bannerAds