---
title: "Web Application on Kubernetes"
description: "Deploy a web application to an existing Kubernetes cluster with Pulumi in TypeScript, Python, Go, C#, YAML, or HCL."
url: "https://www.pulumi.com/dev/templates/kubernetes-application/web-application/"
image: "https://www.pulumi.com/assets/og/dev/templates/kubernetes-application/web-application.png"
---

# Web Application on Kubernetes

Deploy a web application to an existing Kubernetes cluster with Pulumi in TypeScript, Python, Go, C#, YAML, or HCL.

The Kubernetes Web Application template scaffolds a Pulumi project that deploys a web application to an existing Kubernetes cluster using Pulumi's [Kubernetes provider](https://www.pulumi.com/registry/packages/kubernetes). The template creates a new namespace, a ConfigMap with an NGINX configuration, a Deployment to run the application, and a Service that exposes it inside the cluster. The Deployment runs the public `nginx` image as a placeholder app, so the project deploys end to end out of the box.

![An architecture diagram of the Kubernetes Web Application template](./architecture.svg)

## Before you begin

**TypeScript**

For this walkthrough, you'll need:

- [x] The [Pulumi CLI](https://www.pulumi.com/docs/install/)
- [x] Access to a Kubernetes cluster. You can run one locally with [kind](https://kind.sigs.k8s.io/), [minikube](https://minikube.sigs.k8s.io/docs/start/), or [Docker Desktop](https://docs.docker.com/desktop/use-desktop/kubernetes/)
- [x] The [kubectl](https://kubernetes.io/docs/tasks/tools/) CLI
- [x] Permission to create namespaces and workloads in the cluster
- [x] A current version of [Node.js](https://nodejs.org/en/download) and [npm](https://www.npmjs.com/package/npm) installed locally

**Python**

For this walkthrough, you'll need:

- [x] The [Pulumi CLI](https://www.pulumi.com/docs/install/)
- [x] Access to a Kubernetes cluster. You can run one locally with [kind](https://kind.sigs.k8s.io/), [minikube](https://minikube.sigs.k8s.io/docs/start/), or [Docker Desktop](https://docs.docker.com/desktop/use-desktop/kubernetes/)
- [x] The [kubectl](https://kubernetes.io/docs/tasks/tools/) CLI
- [x] Permission to create namespaces and workloads in the cluster
- [x] A current version of [Python](https://www.python.org/downloads/) and [pip](https://pip.pypa.io/en/stable/installation/), [Poetry](https://python-poetry.org/docs/) or [uv](https://docs.astral.sh/uv/getting-started/installation/) installed locally

**Go**

For this walkthrough, you'll need:

- [x] The [Pulumi CLI](https://www.pulumi.com/docs/install/)
- [x] Access to a Kubernetes cluster. You can run one locally with [kind](https://kind.sigs.k8s.io/), [minikube](https://minikube.sigs.k8s.io/docs/start/), or [Docker Desktop](https://docs.docker.com/desktop/use-desktop/kubernetes/)
- [x] The [kubectl](https://kubernetes.io/docs/tasks/tools/) CLI
- [x] Permission to create namespaces and workloads in the cluster
- [x] A current version of [Go](https://go.dev/doc/install) installed locally

**C#**

For this walkthrough, you'll need:

- [x] The [Pulumi CLI](https://www.pulumi.com/docs/install/)
- [x] Access to a Kubernetes cluster. You can run one locally with [kind](https://kind.sigs.k8s.io/), [minikube](https://minikube.sigs.k8s.io/docs/start/), or [Docker Desktop](https://docs.docker.com/desktop/use-desktop/kubernetes/)
- [x] The [kubectl](https://kubernetes.io/docs/tasks/tools/) CLI
- [x] Permission to create namespaces and workloads in the cluster
- [x] A current version of [.NET](https://dotnet.microsoft.com/en-us/download/dotnet) installed locally

**YAML**

For this walkthrough, you'll need:

- [x] The [Pulumi CLI](https://www.pulumi.com/docs/install/)
- [x] Access to a Kubernetes cluster. You can run one locally with [kind](https://kind.sigs.k8s.io/), [minikube](https://minikube.sigs.k8s.io/docs/start/), or [Docker Desktop](https://docs.docker.com/desktop/use-desktop/kubernetes/)
- [x] The [kubectl](https://kubernetes.io/docs/tasks/tools/) CLI
- [x] Permission to create namespaces and workloads in the cluster

**HCL**

For this walkthrough, you'll need:

- [x] A current version of the [Pulumi CLI](https://www.pulumi.com/docs/install/) ([Pulumi HCL](https://www.pulumi.com/docs/iac/languages-sdks/hcl/) requires no additional runtime)
- [x] Access to a Kubernetes cluster. You can run one locally with [kind](https://kind.sigs.k8s.io/), [minikube](https://minikube.sigs.k8s.io/docs/start/), or [Docker Desktop](https://docs.docker.com/desktop/use-desktop/kubernetes/)
- [x] The [kubectl](https://kubernetes.io/docs/tasks/tools/) CLI
- [x] Permission to create namespaces and workloads in the cluster

## Create a new project

Create a new [project](https://www.pulumi.com/docs/iac/concepts/projects/) from the template:

**TypeScript**

```bash
mkdir my-k8s-app; cd my-k8s-app
pulumi new webapp-kubernetes-typescript
```

**Python**

```bash
mkdir my-k8s-app; cd my-k8s-app
pulumi new webapp-kubernetes-python
```

**Go**

```bash
mkdir my-k8s-app; cd my-k8s-app
pulumi new webapp-kubernetes-go
```

**C#**

```bash
mkdir my-k8s-app; cd my-k8s-app
pulumi new webapp-kubernetes-csharp
```

**YAML**

```bash
mkdir my-k8s-app; cd my-k8s-app
pulumi new webapp-kubernetes-yaml
```

**HCL**

```bash
mkdir my-k8s-app; cd my-k8s-app
pulumi new webapp-kubernetes-hcl
```

The `pulumi new` command walks you through creating and configuring the new project and stack. A [stack](https://www.pulumi.com/docs/iac/concepts/stacks/) is an instance of a project, and you can have many of them (`dev`, `staging`, `prod`), each with its own [configuration](https://www.pulumi.com/docs/iac/concepts/config/) settings. Depending on the language, you may also be asked for your preferred package manager or toolchain.

This template's settings include:

**TypeScript / Python / Go / C#**

| Key | Description | Default |
| --- | --- | --- |
| `namespace` | The Kubernetes namespace to deploy into | `webapp` |
| `replicas` | The number of replicas to deploy | `1` |

You can change values like these later with `pulumi config set`:

```bash
pulumi config set namespace <value>
pulumi config set replicas <value>
```

**YAML**

| Key | Description | Default |
| --- | --- | --- |
| `k8sNamespace` | The Kubernetes namespace to deploy into | `webapp` |
| `numReplicas` | The number of replicas to deploy | `1` |

You can change values like these later with `pulumi config set`:

```bash
pulumi config set k8sNamespace <value>
pulumi config set numReplicas <value>
```

**HCL**

| Key | Description | Default |
| --- | --- | --- |
| `k8s_namespace` | The Kubernetes namespace to deploy into | `webapp` |
| `num_replicas` | The number of replicas to deploy | `1` |

You can change values like these later with `pulumi config set`:

```bash
pulumi config set k8s_namespace <value>
pulumi config set num_replicas <value>
```

## Review the code

**TypeScript / Python / Go / C# / HCL**

When setup completes, you'll see a few files:

- `Pulumi.yaml` contains the project name and the language it's written in.
- `Pulumi.dev.yaml` contains the `dev` stack's settings, including the values you just entered.
- `index.ts` contains the program code that declares your Kubernetes resources.

**YAML**

When setup completes, you'll see a few files:

- `Pulumi.yaml` contains the project name and the resources it declares.
- `Pulumi.dev.yaml` contains the `dev` stack's settings, including the values you just entered.

Take a moment to open them up and have a look. Here's what's in `index.ts`:

**TypeScript**

```typescript title="index.ts"
import * as pulumi from "@pulumi/pulumi";
import * as kubernetes from "@pulumi/kubernetes";

// Get some values from the stack configuration, or use defaults
const config = new pulumi.Config();
const k8sNamespace = config.get("namespace") || "webapp";
const numReplicas = config.getNumber("replicas") || 1;
const appLabels = {
    app: "nginx",
};

// Create a new namespace
const webServerNs = new kubernetes.core.v1.Namespace("webserver", {metadata: {
    name: k8sNamespace,
}});

// Create a new ConfigMap for the Nginx configuration
const webServerConfig = new kubernetes.core.v1.ConfigMap("webserverconfig", {
    metadata: {
        namespace: webServerNs.metadata.name,
    },
    data: {
        "nginx.conf": `events { }
http {
  server {
    listen 80;
    root /usr/share/nginx/html;
    index index.html index.htm index.nginx-debian.html
    server_name _;
    location / {
      try_files $uri $uri/ =404;
    }
  }
}
`,
    },
});

// Create a new Deployment with a user-specified number of replicas
const webServerDeployment = new kubernetes.apps.v1.Deployment("webserverdeployment", {
    metadata: {
        namespace: webServerNs.metadata.name,
    },
    spec: {
        selector: {
            matchLabels: appLabels,
        },
        replicas: numReplicas,
        template: {
            metadata: {
                labels: appLabels,
            },
            spec: {
                containers: [{
                    image: "nginx",
                    name: "nginx",
                    volumeMounts: [{
                        mountPath: "/etc/nginx/nginx.conf",
                        name: "nginx-conf-volume",
                        readOnly: true,
                        subPath: "nginx.conf",
                    }],
                }],
                volumes: [{
                    configMap: {
                        items: [{
                            key: "nginx.conf",
                            path: "nginx.conf",
                        }],
                        name: webServerConfig.metadata.name,
                    },
                    name: "nginx-conf-volume",
                }],
            },
        },
    },
});

// Expose the Deployment as a Kubernetes Service
const webServerService = new kubernetes.core.v1.Service("webserverservice", {
    metadata: {
        namespace: webServerNs.metadata.name,
    },
    spec: {
        ports: [{
            port: 80,
            targetPort: 80,
            protocol: "TCP",
        }],
        selector: appLabels,
    },
});

// Export some values for use elsewhere
export const deploymentName = webServerDeployment.metadata.name;
export const serviceName = webServerService.metadata.name;
```

**Python**

```python title="__main__.py"
import pulumi
import pulumi_kubernetes as kubernetes

# Get some values from the Pulumi stack configuration, or use defaults
config = pulumi.Config()
k8sNamespace = config.get("namespace", "webapp")
numReplicas = config.get_int("replicas", 1)
app_labels = {
    "app": "nginx",
}

# Create a namespace
webserverns = kubernetes.core.v1.Namespace(
    "webserver",
    metadata={
        "name": k8sNamespace,
    },
)

# Create a ConfigMap for the Nginx configuration
webserverconfig = kubernetes.core.v1.ConfigMap(
    "webserverconfig",
    metadata={
        "namespace": webserverns.metadata.name,
    },
    data={
        "nginx.conf": """events { }
http {
  server {
    listen 80;
    root /usr/share/nginx/html;
    index index.html index.htm index.nginx-debian.html
    server_name _;
    location / {
      try_files $uri $uri/ =404;
    }
  }
}
""",
    },
)

# Create a Deployment with a user-defined number of replicas
webserverdeployment = kubernetes.apps.v1.Deployment(
    "webserverdeployment",
    metadata={
        "namespace": webserverns.metadata.name,
    },
    spec={
        "selector": {
            "match_labels": app_labels,
        },
        "replicas": numReplicas,
        "template": {
            "metadata": {
                "labels": app_labels,
            },
            "spec": {
                "containers": [
                    {
                        "image": "nginx",
                        "name": "nginx",
                        "volume_mounts": [
                            {
                                "mount_path": "/etc/nginx/nginx.conf",
                                "name": "nginx-conf-volume",
                                "read_only": True,
                                "sub_path": "nginx.conf",
                            }
                        ],
                    }
                ],
                "volumes": [
                    {
                        "config_map": {
                            "items": [
                                {
                                    "key": "nginx.conf",
                                    "path": "nginx.conf",
                                }
                            ],
                            "name": webserverconfig.metadata.name,
                        },
                        "name": "nginx-conf-volume",
                    }
                ],
            },
        },
    },
)

# Expose the Deployment as a Kubernetes Service
webserverservice = kubernetes.core.v1.Service(
    "webserverservice",
    metadata={
        "namespace": webserverns.metadata.name,
    },
    spec={
        "ports": [
            {
                "port": 80,
                "target_port": 80,
                "protocol": "TCP",
            }
        ],
        "selector": app_labels,
    },
)

# Export some values for use elsewhere
pulumi.export("deploymentName", webserverdeployment.metadata.name)
pulumi.export("serviceName", webserverservice.metadata.name)
```

**Go**

```go title="main.go"
package main

import (
	appsv1 "github.com/pulumi/pulumi-kubernetes/sdk/v4/go/kubernetes/apps/v1"
	corev1 "github.com/pulumi/pulumi-kubernetes/sdk/v4/go/kubernetes/core/v1"
	metav1 "github.com/pulumi/pulumi-kubernetes/sdk/v4/go/kubernetes/meta/v1"
	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
	"github.com/pulumi/pulumi/sdk/v3/go/pulumi/config"
)

func main() {
	pulumi.Run(func(ctx *pulumi.Context) error {
		// Get some configuration values from the Pulumi stack, or use defaults
		cfg := config.New(ctx, "")
		k8sNamespace, err := cfg.Try("namespace")
		if err != nil {
			k8sNamespace = "webapp"
		}
		numReplicas, err := cfg.TryInt("replicas")
		if err != nil {
			numReplicas = 1
		}
		appLabels := pulumi.StringMap{
			"app": pulumi.String("nginx"),
		}

		// Create a new namespace
		webServerNs, err := corev1.NewNamespace(ctx, "webserverns", &corev1.NamespaceArgs{
			Metadata: &metav1.ObjectMetaArgs{
				Name: pulumi.String(k8sNamespace),
			},
		})
		if err != nil {
			return err
		}

		// Create a new ConfigMap for the Nginx configuration
		webServerConfig, err := corev1.NewConfigMap(ctx, "webserverconfig", &corev1.ConfigMapArgs{
			Metadata: &metav1.ObjectMetaArgs{
				Namespace: webServerNs.Metadata.Name(),
			},
			Data: pulumi.StringMap{
				"nginx.conf": pulumi.Sprintf(`events { }
http {
  server {
    listen 80;
    root /usr/share/nginx/html;
    index index.html index.htm index.nginx-debian.html
    server_name _;
    location / {
      try_files $uri $uri/ =404;
    }
  }
}
`),
			},
		})
		if err != nil {
			return err
		}

		// Create a new Deployment with a user-specified number of replicas
		webServerDeployment, err := appsv1.NewDeployment(ctx, "webserverdeployment", &appsv1.DeploymentArgs{
			Metadata: &metav1.ObjectMetaArgs{
				Namespace: webServerNs.Metadata.Name(),
			},
			Spec: &appsv1.DeploymentSpecArgs{
				Selector: &metav1.LabelSelectorArgs{
					MatchLabels: pulumi.StringMap(appLabels),
				},
				Replicas: pulumi.Int(numReplicas),
				Template: &corev1.PodTemplateSpecArgs{
					Metadata: &metav1.ObjectMetaArgs{
						Labels: pulumi.StringMap(appLabels),
					},
					Spec: &corev1.PodSpecArgs{
						Containers: corev1.ContainerArray{
							&corev1.ContainerArgs{
								Image: pulumi.String("nginx"),
								Name:  pulumi.String("nginx"),
								VolumeMounts: corev1.VolumeMountArray{
									&corev1.VolumeMountArgs{
										MountPath: pulumi.String("/etc/nginx/nginx.conf"),
										Name:      pulumi.String("nginx-conf-volume"),
										ReadOnly:  pulumi.Bool(true),
										SubPath:   pulumi.String("nginx.conf"),
									},
								},
							},
						},
						Volumes: corev1.VolumeArray{
							&corev1.VolumeArgs{
								ConfigMap: &corev1.ConfigMapVolumeSourceArgs{
									Items: corev1.KeyToPathArray{
										&corev1.KeyToPathArgs{
											Key:  pulumi.String("nginx.conf"),
											Path: pulumi.String("nginx.conf"),
										},
									},
									Name: webServerConfig.Metadata.Name(),
								},
								Name: pulumi.String("nginx-conf-volume"),
							},
						},
					},
				},
			},
		})
		if err != nil {
			return err
		}

		// Expose the Deployment as a Kubernetes Service
		webServerService, err := corev1.NewService(ctx, "webserverservice", &corev1.ServiceArgs{
			Metadata: &metav1.ObjectMetaArgs{
				Namespace: webServerNs.Metadata.Name(),
			},
			Spec: &corev1.ServiceSpecArgs{
				Ports: corev1.ServicePortArray{
					&corev1.ServicePortArgs{
						Port:       pulumi.Int(80),
						TargetPort: pulumi.Any(80),
						Protocol:   pulumi.String("TCP"),
					},
				},
				Selector: pulumi.StringMap(appLabels),
			},
		})
		if err != nil {
			return err
		}

		// Export some values for use elsewhere
		ctx.Export("deploymentName", webServerDeployment.Metadata.Name())
		ctx.Export("serviceName", webServerService.Metadata.Name())

		return nil
	})
}
```

**C#**

```csharp title="Program.cs"
using System.Collections.Generic;
using Pulumi;
using Kubernetes = Pulumi.Kubernetes;

return await Deployment.RunAsync(() => 
{
    var config = new Config();
    var k8sNamespace = config.Get("namespace") ?? "webapp";
    var numReplicas = config.GetInt32("replicas") ?? 1;
    var appLabels = new InputMap<string>
    {
        { "app", "nginx" },
    };

    var webserverNs = new Kubernetes.Core.V1.Namespace("webserverNs", new()
    {
        Metadata = new Kubernetes.Types.Inputs.Meta.V1.ObjectMetaArgs
        {
            Name = @k8sNamespace,
        },
    });

    var webserverconfig = new Kubernetes.Core.V1.ConfigMap("webserverconfig", new()
    {
        Metadata = new Kubernetes.Types.Inputs.Meta.V1.ObjectMetaArgs
        {
            Namespace = webserverNs.Metadata.Apply(m => m.Name),
        },
        Data = 
        {
            { "nginx.conf", @"events { }
http {
  server {
    listen 80;
    root /usr/share/nginx/html;
    index index.html index.htm index.nginx-debian.html
    server_name _;
    location / {
      try_files $uri $uri/ =404;
    }
  }
}
" },
        },
    });

    var webserverdeployment = new Kubernetes.Apps.V1.Deployment("webserverdeployment", new()
    {
        Metadata = new Kubernetes.Types.Inputs.Meta.V1.ObjectMetaArgs
        {
            Namespace = webserverNs.Metadata.Apply(m => m.Name),
        },
        Spec = new Kubernetes.Types.Inputs.Apps.V1.DeploymentSpecArgs
        {
            Selector = new Kubernetes.Types.Inputs.Meta.V1.LabelSelectorArgs
            {
                MatchLabels = appLabels,
            },
            Replicas = numReplicas,
            Template = new Kubernetes.Types.Inputs.Core.V1.PodTemplateSpecArgs
            {
                Metadata = new Kubernetes.Types.Inputs.Meta.V1.ObjectMetaArgs
                {
                    Labels = appLabels,
                },
                Spec = new Kubernetes.Types.Inputs.Core.V1.PodSpecArgs
                {
                    Containers = new[]
                    {
                        new Kubernetes.Types.Inputs.Core.V1.ContainerArgs
                        {
                            Image = "nginx",
                            Name = "nginx",
                            VolumeMounts = new[]
                            {
                                new Kubernetes.Types.Inputs.Core.V1.VolumeMountArgs
                                {
                                    MountPath = "/etc/nginx/nginx.conf",
                                    Name = "nginx-conf-volume",
                                    ReadOnly = true,
                                    SubPath = "nginx.conf",
                                },
                            },
                        },
                    },
                    Volumes = new[]
                    {
                        new Kubernetes.Types.Inputs.Core.V1.VolumeArgs
                        {
                            ConfigMap = new Kubernetes.Types.Inputs.Core.V1.ConfigMapVolumeSourceArgs
                            {
                                Items = new[]
                                {
                                    new Kubernetes.Types.Inputs.Core.V1.KeyToPathArgs
                                    {
                                        Key = "nginx.conf",
                                        Path = "nginx.conf",
                                    },
                                },
                                Name = webserverconfig.Metadata.Apply(m => m.Name),
                            },
                            Name = "nginx-conf-volume",
                        },
                    },
                },
            },
        },
    });

    var webserverservice = new Kubernetes.Core.V1.Service("webserverservice", new()
    {
        Metadata = new Kubernetes.Types.Inputs.Meta.V1.ObjectMetaArgs
        {
            Namespace = webserverNs.Metadata.Apply(m => m.Name),
        },
        Spec = new Kubernetes.Types.Inputs.Core.V1.ServiceSpecArgs
        {
            Ports = new[]
            {
                new Kubernetes.Types.Inputs.Core.V1.ServicePortArgs
                {
                    Port = 80,
                    TargetPort = 80,
                    Protocol = "TCP",
                },
            },
            Selector = appLabels,
        },
    });

    return new Dictionary<string, object?>
    {
        ["deploymentName"] = webserverdeployment.Metadata.Apply(metadata => metadata?.Name),
        ["serviceName"] = webserverservice.Metadata.Apply(metadata => metadata?.Name),
    };
});
```

**YAML**

```yaml title="Pulumi.yaml"
name: my-project
description: A Pulumi YAML program to deploy a web application onto a Kubernetes cluster
runtime: yaml
config:
  k8sNamespace:
    default: webapp
    type: string
  numReplicas:
    default: 1
    type: integer

variables:
  appLabels:
    app: nginx

resources:
  # Create a new namespace for the resources
  webserverns:
    type: kubernetes:core/v1:Namespace
    properties:
      metadata:
        name: ${k8sNamespace}
  # Create a ConfigMap to store Nginx configuration
  webserverconfig:
    type: kubernetes:core/v1:ConfigMap
    properties:
      metadata:
        namespace: ${webserverns.metadata.name}
      data: 
        nginx.conf: |
          events { }
          http {
            server {
              listen 80;
              root /usr/share/nginx/html;
              index index.html index.htm index.nginx-debian.html
              server_name _;
              location / {
                try_files $uri $uri/ =404;
              }
            }
          }
  # Create a new Deployment
  webserverdeployment:
    type: kubernetes:apps/v1:Deployment
    properties:
      metadata:
        namespace: ${webserverns.metadata.name}
      spec:
        selector:
          matchLabels: ${appLabels}
        replicas: ${numReplicas}
        template:
          metadata:
            labels: ${appLabels}
          spec:
            containers:
            - image: nginx
              name: nginx
              volumeMounts:
              - mountPath: /etc/nginx/nginx.conf
                name: nginx-conf-volume
                readOnly: true
                subPath: nginx.conf
            volumes:
            - configMap:
                items:
                - key: nginx.conf
                  path: nginx.conf
                name: ${webserverconfig.metadata.name}
              name: nginx-conf-volume
  # Expose the Deployment as a Kubernetes Service
  webserverservice:
    type: kubernetes:core/v1:Service
    properties:
      metadata:
        namespace: ${webserverns.metadata.name}
      spec:
        ports: [{ port: 80, targetPort: 80, protocol: "TCP" }]
        selector: ${appLabels}

# Export some values for use elsewhere
outputs:
  deploymentName: ${webserverdeployment.metadata.name}
  serviceName: ${webserverservice.metadata.name}
```

**HCL**

```hcl title="main.tf"
terraform {
  required_providers {
    kubernetes = {
      source = "pulumi/kubernetes"
    }
  }
}

variable "k8s_namespace" {
  description = "The Kubernetes namespace to deploy into"
  type        = string
  default     = "webapp"
}

variable "num_replicas" {
  description = "The number of replicas to deploy"
  type        = number
  default     = 1
}

locals {
  app_labels = {
    app = "nginx"
  }
}

# Create a new namespace for the resources
resource "kubernetes_core_v1_namespace" "webserverns" {
  metadata = {
    name = var.k8s_namespace
  }
}

# Create a ConfigMap to store Nginx configuration
resource "kubernetes_core_v1_config_map" "webserverconfig" {
  metadata = {
    namespace = kubernetes_core_v1_namespace.webserverns.metadata.name
  }

  data = {
    "nginx.conf" = <<-EOF
      events { }
      http {
        server {
          listen 80;
          root /usr/share/nginx/html;
          index index.html index.htm index.nginx-debian.html;
          server_name _;
          location / {
            try_files $uri $uri/ =404;
          }
        }
      }
    EOF
  }
}

# Create a new Deployment
resource "kubernetes_apps_v1_deployment" "webserverdeployment" {
  metadata = {
    namespace = kubernetes_core_v1_namespace.webserverns.metadata.name
  }

  spec = {
    replicas = var.num_replicas
    selector = {
      match_labels = local.app_labels
    }
    template = {
      metadata = {
        labels = local.app_labels
      }
      spec = {
        containers = [{
          name  = "nginx"
          image = "nginx"
          volume_mounts = [{
            name       = "nginx-conf-volume"
            mount_path = "/etc/nginx/nginx.conf"
            sub_path   = "nginx.conf"
            read_only  = true
          }]
        }]
        volumes = [{
          name = "nginx-conf-volume"
          config_map = {
            name = kubernetes_core_v1_config_map.webserverconfig.metadata.name
            items = [{
              key  = "nginx.conf"
              path = "nginx.conf"
            }]
          }
        }]
      }
    }
  }
}

# Expose the Deployment as a Kubernetes Service
resource "kubernetes_core_v1_service" "webserverservice" {
  metadata = {
    namespace = kubernetes_core_v1_namespace.webserverns.metadata.name
  }

  spec = {
    selector = local.app_labels
    ports = [{
      port        = 80
      target_port = 80
      protocol    = "TCP"
    }]
  }
}

# Export some values for use elsewhere
output "deployment_name" {
  value = kubernetes_apps_v1_deployment.webserverdeployment.metadata.name
}

output "service_name" {
  value = kubernetes_core_v1_service.webserverservice.metadata.name
}
```

## Deploy the project

The program deploys into the cluster your current kubeconfig context points at. Check which cluster that is before you deploy:

```bash
$ kubectl config current-context
```

Deploy with [`pulumi up`](https://www.pulumi.com/docs/iac/cli/commands/pulumi_up). It starts with a preview of what it's about to create and asks before it changes anything. Choose `yes` to deploy.

```bash
$ pulumi up
```

Pulumi adds a random suffix to most resource names, so the Deployment `webserverdeployment` becomes something like `webserverdeployment-4f8a2c1d`. This is [autonaming](https://www.pulumi.com/docs/iac/concepts/resources/names/#autonaming). It lets you deploy the same program to more than one stack, and lets Pulumi create a replacement before it deletes the old resource, without names colliding. The namespace is the exception: the program gives it the exact name you entered (`webapp` by default), so a second stack in the same cluster needs a different one.

When it finishes, Pulumi prints the stack's [outputs](https://www.pulumi.com/docs/iac/concepts/stacks/#outputs), values it only knows once the resources exist:

**TypeScript / Python / Go / C# / YAML**

**`deploymentName`**

The name of your new Kubernetes Deployment.

**`serviceName`**

The name of your new Kubernetes Service.

**HCL**

**`deployment_name`**

The name of your new Kubernetes Deployment.

**`service_name`**

The name of your new Kubernetes Service.

Read one any time with `pulumi stack output <name>`, or pass it to another command. This one looks up the Deployment in the `webapp` namespace (change `-n` if you entered another). `READY` shows `1/1` once its pod is running:

**TypeScript / Python / Go / C# / YAML**

```bash
$ kubectl get deployment $(pulumi stack output deploymentName) -n webapp
```

**HCL**

```bash
$ kubectl get deployment $(pulumi stack output deployment_name) -n webapp
```

**Need help?**

If `pulumi up` reports that the cluster is unreachable, check which cluster `kubectl` points to and whether it's running:

```bash
$ kubectl config current-context
$ kubectl cluster-info
```

Restart your local cluster if necessary, or switch to another cluster with `kubectl config use-context <CONTEXT_NAME>`.

Still stuck? [Let us know](https://github.com/pulumi/docs/issues/new).

## Customize the project

Projects created with this template expose the following [configuration](https://www.pulumi.com/docs/iac/concepts/config/) settings:

**TypeScript / Python / Go / C#**

**`namespace`**

The name of the namespace to be created in your existing cluster. Defaults to `webapp`.

**`replicas`**

The number of replicated Pods to be created in your new Deployment. Defaults to `1`.

**YAML**

**`k8sNamespace`**

The name of the namespace to be created in your existing cluster. Defaults to `webapp`.

**`numReplicas`**

The number of replicated Pods to be created in your new Deployment. Defaults to `1`.

**HCL**

**`k8s_namespace`**

The name of the namespace to be created in your existing cluster. Defaults to `webapp`.

**`num_replicas`**

The number of replicated Pods to be created in your new Deployment. Defaults to `1`.

All of these settings are optional and may be adjusted either by editing the stack configuration file directly (by default, `Pulumi.dev.yaml`) or by changing their values with [`pulumi config set`](https://www.pulumi.com/docs/iac/cli/commands/pulumi_config_set).

For example, run three pods, then look at the Deployment again; `READY` shows `3/3`:

**TypeScript / Python / Go / C#**

```bash
$ pulumi config set replicas 3
$ pulumi up
$ kubectl get deployment $(pulumi stack output deploymentName) -n webapp
```

**YAML**

```bash
$ pulumi config set numReplicas 3
$ pulumi up
$ kubectl get deployment $(pulumi stack output deploymentName) -n webapp
```

**HCL**

```bash
$ pulumi config set num_replicas 3
$ pulumi up
$ kubectl get deployment $(pulumi stack output deployment_name) -n webapp
```

To see what else you can add, browse the [Kubernetes provider](https://www.pulumi.com/registry/packages/kubernetes/) in the Pulumi Registry.

## Cleaning up

You can cleanly destroy the stack and all of its infrastructure with [`pulumi destroy`](https://www.pulumi.com/docs/iac/cli/commands/pulumi_destroy):

```bash
$ pulumi destroy
```

## Learn more

- Browse other architecture templates in the [Templates gallery](https://www.pulumi.com/templates).
- Explore the [Kubernetes provider API docs](https://www.pulumi.com/registry/packages/kubernetes) in the Pulumi Registry.
- Walk through Pulumi from the ground up in [Pulumi Tutorials](https://www.pulumi.com/dev/browse/?type=tutorial).
- Read the latest [Kubernetes posts on the Pulumi blog](https://www.pulumi.com/blog/tag/kubernetes).
