<p>I'm trying to understand why kubernetes docs <a href="https://kubernetes.io/docs/concepts/cluster-administration/manage-deployment/#organizing-resource-configurations" rel="noreferrer">recommend</a> to specify service before deployment in one configuration file:</p>

<blockquote>
  <p>The resources will be created in the order they appear in the file. Therefore, it’s best to specify the service first, since that will ensure the scheduler can spread the pods associated with the service as they are created by the controller(s), such as Deployment.</p>
</blockquote>

<p>Does it mean spread pods between kubernetes cluster nodes?</p>

<p>I tested with the following configuration where a deployment is located before a service and pods are distributed between nods without any issues. </p>

<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: incorrect-order
  namespace: test
spec:
  selector:
    matchLabels:
      app: incorrect-order
  replicas: 2
  template:
    metadata:
      labels:
        app: incorrect-order
    spec:
      containers:
      - name: incorrect-order
        image: nginx
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: incorrect-order
  namespace: test
  labels:
    app: incorrect-order
spec:
  type: NodePort
  ports:
  - port: 80
  selector:
    app: incorrect-order
</code></pre>

<p>Another <a href="https://kubernetes.io/docs/concepts/configuration/overview/#services" rel="noreferrer">explanation</a> is that some environment variables with service URL will not be set for pods in this case. However it also works ok in case a configuration is inside one file like the example above.</p>

<p>Could you please explain why it is better to specify service before the deployment in case of one configuration file? Or may be it is some outdated recommendation.</p>

<p>If you use <code>DNS</code> as service discovery, the order of creation doesn't matter.</p>

<p>In case of <code>Environment Vars</code> (the second way K8S offers service discovery) the order matters, because once that vars are passed to the <strong>starting</strong> pod, they cannot be modified later if the service definition changes.</p>

<p>So if your service is deployed <strong>before</strong> you start your pod, the service envvars are injected inside the linked pod.</p>

<p>If you create a Pod/Deployment resource with labels, this resource will be exposed through a service once this last is created (with proper selector to indicate what resource to expose).</p>
