Kubernetes - can a Deployment contain a Service?

11/10/2018

Just finished reading Nigel Poulton's The Kubernetes Book, but I am somewhat puzzled with Services.

Could a Service be added to the Deployment manifest below somehow?Or does the Service have to be POSTed on its own? Isn't the whole purpose of a deployment to specify everything needed for the app to run?

apiVersion: apps/v1beta2
kind: Deployment
metadata: 
  name: hello-deploy
spec:
  replicas: 10
  selector:
    matchLabels:
      app: hello-world
  minReadySeconds: 10
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1
      maxSurge: 1
  template:
    metadata:
      labels:
        app: hello-world
    spec:
      containers:
      - name: hello-pod
        image: nigelpoulton/k8sbook : latest
        ports:
        - containerPort: 8080
-- HashRocketSyntax
kubernetes
microservices

2 Answers

11/11/2018

Isn't the whole purpose of a deployment to specify everything needed for the app to run?

The whole purpose of "Deployment" is to manage the deployment of pods/replicasets including replication, scaling, rolling update, rollbacks. The DeploymentController is part of the master node's controller manager, and it makes sure that the current state always matches the desired state.

does the Service have to be POSTed on its own?

If you are familiar with Load balancers terminology, Services are frontends and Pods are its backends. Since it is frontend, Service forwards requests to its backend (pods).

-- Abdennour TOUMI
Source: StackOverflow

11/10/2018

They're different objects and you have to submit them separately (HTTP POST, kubectl apply, ...).

There are a couple of tricks you can do to minimize the impact of this:

  • You can use a multi-document YAML file and submit that as a single thing, like

    ---
    apiVersion: apps/v1
    kind: Deployment
    ...
    ---
    apiVersion: v1
    kind: Service
    ...
  • There is an undocumented kind: List that could embed multiple objects

    apiVersion: v1
    kind: List
    items:
      - apiVersion: apps/v1
        kind: Deployment
        ...
      - apiVersion: v1
        kind: Service
        ...
  • You can use a higher-level deployment manager such as Helm that lets you keep each object in a separate file, but deploy them in a single command.

It's perhaps unfortunate that a couple of Kubernetes objects have names that are different from their plain English meanings (a Deployment doesn't cover all of the steps or parts of deploying a whole application; a Service is just an IP/DNS pointer and not a service implementation) but that's the way it is. I tend to capitalize the Kubernetes object names when it will disambiguate things.

-- David Maze
Source: StackOverflow